Skip to content

Commit 16debf2

Browse files
committed
fixed broken shuffle for arrays of length 1 or 0
Coffeescript's range evaluator (in this case [a.length-1..1]) produces inappropriate results for Fisher-Yates when the array is length 1 or 0. The unfixed shuffle pushes undefined values onto the the array. A length check is necessary to continue with this style.
1 parent d2c97b2 commit 16debf2

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

chapters/arrays/shuffling-array-elements.md

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,13 @@ the algorithm.
1818

1919
{% highlight coffeescript %}
2020
shuffle = (a) ->
21-
# From the end of the list to the beginning, pick element `i`.
22-
for i in [a.length-1..1]
23-
# Choose random element `j` to the front of `i` to swap with.
24-
j = Math.floor Math.random() * (i + 1)
25-
# Swap `j` with `i`, using destructured assignment
26-
[a[i], a[j]] = [a[j], a[i]]
21+
if a.length >= 2
22+
# From the end of the list to the beginning, pick element `i`.
23+
for i in [a.length-1..1]
24+
# Choose random element `j` to the front of `i` to swap with.
25+
j = Math.floor Math.random() * (i + 1)
26+
# Swap `j` with `i`, using destructured assignment
27+
[a[i], a[j]] = [a[j], a[i]]
2728
# Return the shuffled array.
2829
a
2930

0 commit comments

Comments
 (0)