De Bruijn sequences: Difference between revisions

+Racket
(Added Perl example)
(+Racket)
Line 416:
Pin number 5814 missing
Pin number 8145 missing
</pre>
 
=={{header|Racket}}==
 
{{trans|Go}}
 
<lang racket>#lang racket
(define (de-bruijn k n)
(define a (make-vector (* k n) 0))
(define seq '())
(define (db t p)
(cond
[(> t n) (when (= (modulo n p) 0)
(set! seq (cons (call-with-values
(thunk (vector->values a 1 (add1 p)))
list)
seq)))]
[else (vector-set! a t (vector-ref a (- t p)))
(db (add1 t) p)
(for ([j (in-range (add1 (vector-ref a (- t p))) k)])
(vector-set! a t j)
(db (add1 t) t))]))
(db 1 1)
(define seq* (append* (reverse seq)))
(append seq* (take seq* (sub1 n))))
 
(define seq (de-bruijn 10 4))
(printf "The length of the de Bruijn sequence is ~a\n\n" (length seq))
(printf "The first 130 digits of the de Bruijn sequence are:\n~a\n\n"
(take seq 130))
(printf "The last 130 digits of the de Bruijn sequence are:\n~a\n\n"
(take-right seq 130))
 
(define (validate name seq)
(printf "Validating the ~ade Bruijn sequence:\n" name)
(define expected (for/set ([i (in-range 0 10000)]) i))
(define actual (for/set ([a (in-list seq)]
[b (in-list (rest seq))]
[c (in-list (rest (rest seq)))]
[d (in-list (rest (rest (rest seq))))])
(+ (* 1000 a) (* 100 b) (* 10 c) d)))
(define diff (set-subtract expected actual))
(cond
[(set-empty? diff) (printf " No errors found\n")]
[else (for ([n (in-set diff)])
(printf " ~a is missing\n" (~a n #:width 4 #:pad-string "0")))])
(newline))
 
(validate "" seq)
(validate "reversed " (reverse seq))
(validate "overlaid " (list-update seq 4443 add1))</lang>
 
{{out}}
 
<pre>
The length of the de Bruijn sequence is 10003
 
The first 130 digits of the de Bruijn sequence are:
(0 0 0 0 1 0 0 0 2 0 0 0 3 0 0 0 4 0 0 0 5 0 0 0 6 0 0 0 7 0 0 0 8 0 0 0 9 0 0 1 1 0 0 1 2 0 0 1 3 0 0 1 4 0 0 1 5 0 0 1 6 0 0 1 7 0 0 1 8 0 0 1 9 0 0 2 1 0 0 2 2 0 0 2 3 0 0 2 4 0 0 2 5 0 0 2 6 0 0 2 7 0 0 2 8 0 0 2 9 0 0 3 1 0 0 3 2 0 0 3 3 0 0 3 4 0 0 3 5 0)
 
The last 130 digits of the de Bruijn sequence are:
(6 8 9 8 6 8 9 9 6 9 6 9 7 7 6 9 7 8 6 9 7 9 6 9 8 7 6 9 8 8 6 9 8 9 6 9 9 7 6 9 9 8 6 9 9 9 7 7 7 7 8 7 7 7 9 7 7 8 8 7 7 8 9 7 7 9 8 7 7 9 9 7 8 7 8 7 9 7 8 8 8 7 8 8 9 7 8 9 8 7 8 9 9 7 9 7 9 8 8 7 9 8 9 7 9 9 8 7 9 9 9 8 8 8 8 9 8 8 9 9 8 9 8 9 9 9 9 0 0 0)
 
Validating the de Bruijn sequence:
No errors found
 
Validating the reversed de Bruijn sequence:
No errors found
 
Validating the overlaid de Bruijn sequence:
1459 is missing
4591 is missing
8145 is missing
5814 is missing
</pre>
 
Anonymous user