Durstenfeld's Algorithm: We Start With All 7 Items. We Randomly Switch The 4 and 7 Items
Durstenfeld's Algorithm: We Start With All 7 Items. We Randomly Switch The 4 and 7 Items
Durstenfeld’s Algorithm is an efficient method to randomly organize a vector of elements. It might be
used to randomize, for example, the play list on your iPod without repeating a song.
The steps below outline an example using the seven dwarves.
Doc
Grumpy
We start with all 7 items.
Happy
We randomly switch the
Sleepy
4th and 7th items.
Bashful
Sneezy
Dopey
The first step is to choose a random number r between 1 and 7 (inclusive). Let’s say we pick r = 4
(obviously, this will vary and that’s what makes this a random process). You could use Excel’s
RandBetween function. We then swap the 4th and the 7th rows to create the following.
Doc
Grumpy Now we focus on the
Happy remaining 6 items. We
Dopey randomly switch the 2nd
and 6th positions.
Bashful
Sneezy
Sleepy
Next, we will choose a random number between 1 and 6 (so “Sleepy” is set for good in the 7th position).
Let’s say we get r = 2. Again, this will be random. We now swap the second item with the 6th item to
obtain the following:
Doc
Sneezy
Happy
Dopey
Bashful
Grumpy
Sleepy
And we keep going, choosing a random number between 1 and 5 (my example uses r = 1 so we swap
rows 1 and 5), then a random number between 1 and 4 (my example uses r = 1 again so we swap rows 1
and 4), then a random number between 1 and 3 (my example uses r = 2 so we swap rows 2 and 3), and
finally a random number between 1 and 2 (inclusive, my example uses 2, so we swap rows 2 and 2 – this
does nothing). The figure below depicts what is happening as we do this.
Doc Bashful Dopey Dopey Dopey
Sneezy Sneezy Sneezy Happy Happy
Happy Happy Happy Sneezy Sneezy
Dopey Dopey Bashful Bashful Bashful
Bashful Doc Doc Doc Doc
Grumpy Grumpy Grumpy Grumpy Grumpy
Sleepy Sleepy Sleepy Sleepy Sleepy
The approach is to count the number of elements to be randomized (let’s call this n), then iterate
through an index variable (let’s call this j). You may have noticed a pattern that emerges in a count‐
controlled iteration (think For…Next loop!). If we use an index j then we always choose a random
number between 1 and (n – j + 1) (convince yourself of this as j goes from 1 to 7). Second, we always
swap the (n – j + 1)th element with our randomly assigned element.
Swapping is easy in VBA. If I wanted to swap element A(2) with A(5) you could just do the following:
temp = A(2)
A(2) = A(5)
A(5) = temp