Galton box animation: Difference between revisions

Content added Content deleted
Line 1,358: Line 1,358:
;state of simulation...list of all positions and vector of balls (index = bin)
;state of simulation...list of all positions and vector of balls (index = bin)
(define-struct st (poss bins))
(define-struct st (poss bins))
;given list of indices, increment those by 1
;increment vector @i
(define (vector-inc-indices! is v)
(define (vector-inc! v i) (vector-set! v i (add1 (vector-ref v i))))
(let vector-inc-indices ([is is])
(if (null? is)
v
(begin (vector-set! v (car is) (add1 (vector-ref v (car is))))
(vector-inc-indices (cdr is))))))


(define BALL-RADIUS 6)
(define BALL-RADIUS 6)
Line 1,464: Line 1,459:
;dead balls have (partition from normal Racket would be useful here...)
;dead balls have (partition from normal Racket would be useful here...)
[dead (filter (λ (p) (>= (pos-row p) height)) new-ps)]
[dead (filter (λ (p) (>= (pos-row p) height)) new-ps)]
;map col to bin index
;adjust col from [-x,x] to [0,2x]
[bin-indices (map (λ (p) (quotient (+ (pos-col p) height) 2)) dead)])
[bin-indices (map (λ (p) (quotient (+ (pos-col p) height) 2)) dead)])
;add new balls to the live balls
;add new balls to the live balls
(make-st (append (make-list (random 4) (make-pos 0 0)) live)
(make-st (append (make-list (random 4) (make-pos 0 0)) live)
;sum dead ball positions into bins
;sum dead ball positions into bins
(vector-inc-indices! bin-indices (st-bins s)))))
(begin (for-each (λ (i) (vector-inc! (st-bins s) i)) bin-indices)
(st-bins s)))))


;run simulation with empty list of positions to start, stepping with "tock" and drawing with "draw"
;run simulation with empty list of positions to start, stepping with "tock" and drawing with "draw"