# [plt-scheme] Scheme implementation of Fisher-Yates shuffle

Hello all,
Here is my Scheme implementation of the "modern" version of the "Fisher
Yates Shuffle"
(http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle). I am
sharing this with the hope that it may be useful to someone in the
community.
<code>
#lang scheme
;; Fisher-Yates shuffling algorithm in Scheme (plt-scheme)
;; Amit Saha (http://amitksaha.wordpress.com; amitsaha.in at gmail.com)
;; Useful to obtain a random shuffle of a list
;; call with (shuffle <your list>)
(define (shuffle deck)
(let loop ((n (length deck)) (shuff_deck (list->vector deck)))
(if (<= n 1)
shuff_deck
(begin
(set! n (- n 1))
(let* ([rand (random (+ 1 n))]
[tmp (vector-ref shuff_deck rand)]
)
(vector-set! shuff_deck rand (vector-ref shuff_deck n))
(vector-set! shuff_deck n tmp))
(loop n shuff_deck)))))
</code>
At the same time, I would appreciate any feedback on the implementation.
Best Regards,
Amit
--
Journal: http://amitksaha.wordpress.com
µ-blog: http://twitter.com/amitsaha
IRC: cornucopic on #scheme, #lisp, #math, #linux