Download code

Jump to: navigation, search

Back to Sierpinski_triangle_(Scheme)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

cellular.sc

 1 (define (state->string astate)
 2   (list->string (map (lambda (x) (if (= x 0) #\space #\@)) 
 3                      (vector->list astate))))
 4 
 5 (define *init-state* #80(0))
 6 (vector-set! *init-state* 40 1)
 7 
 8 (define *rules*
 9   '(((0 0 0) . 0)
10     ((0 0 1) . 1)
11     ((0 1 0) . 1)
12     ((0 1 1) . 1)
13     ((1 0 0) . 1)
14     ((1 0 1) . 1)
15     ((1 1 0) . 1)
16     ((1 1 1) . 0)))
17 (define (vector-wrap-ref vec position)
18   (vector-ref vec (modulo position (vector-length vec))))
19 
20 (define (get-neighbors state position)
21   (map (lambda (x) (vector-wrap-ref state (+ x position))) 
22        (list -1 0 1)))
23 (define (state->neighbor-list state)
24   (define (list-builder pos accum-list)
25     (if (< pos 0) 
26         accum-list
27         (list-builder (- pos 1) (cons (get-neighbors state pos) accum-list))))
28     (list-builder (- (vector-length state) 1) (list)))
29 
30 (define (apply-rules neighbor-list)
31   (list->vector (map (lambda (neighbors) (cdr (assoc neighbors *rules*))) neighbor-list)))
32 (define (run-and-display state iters)
33   (begin
34     (display (state->string state))
35     (newline)
36     (if (= iters 0) 
37         (display "end")
38         (run-and-display (apply-rules (state->neighbor-list state)) (- iters 1)))))
39 
40 ;; we might call it like this:
41 
42 (run-and-display *init-state* 31)


hijacker
hijacker
hijacker
hijacker