Skip to content

Instantly share code, notes, and snippets.

@penryu
Created September 17, 2011 08:34
Show Gist options
  • Save penryu/1223760 to your computer and use it in GitHub Desktop.
Save penryu/1223760 to your computer and use it in GitHub Desktop.
Playing with the Fisher-Yates shuffle and named lets. Comments/corrections welcome.
(define (vector-swap! v idx1 idx2)
(let ((temp (vector-ref v idx1)))
(cond ((= idx1 idx2) v)
(else (vector-set! v idx1 (vector-ref v idx2))
(vector-set! v idx2 temp)
v))))
(define (vector-shuffle! vec)
(let vec-shuf-helper ([v vec]
[n (vector-length vec)])
(if (<= n 1) v
(vec-shuf-helper
(vector-swap! v (- n 1) (random n))
(- n 1)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment