[plt-scheme] Re: Scheme implementation of Fisher-Yates shuffle

From: Amit Saha (lists.amitsaha at gmail.com)
Date: Sun Aug 9 10:09:55 EDT 2009

Amit Saha wrote:
> 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.

Was also interested in the background of the implementation of 
'shuffle-list' in 'games/cards'. I checked the 'utils.ss' file, but 
didn't find any references.

Best Regards,
Amit
-- 
Journal: http://amitksaha.wordpress.com
µ-blog: http://twitter.com/amitsaha
IRC: cornucopic on #scheme, #lisp, #math, #linux


Posted on the users mailing list.