Skip to content

Commit 6988fe0

Browse files
committed
Clarify shuffle code
Better variable names, Removed silly comments, Expanded explination of @malgorithms commit 16debf2 in comments
1 parent 291275c commit 6988fe0

File tree

1 file changed

+10
-10
lines changed

1 file changed

+10
-10
lines changed

Diff for: chapters/arrays/shuffling-array-elements.md

+10-10
Original file line numberDiff line numberDiff line change
@@ -17,16 +17,16 @@ at the end of the list. This [Fisher-Yates shuffle Visualization] may help you u
1717
the algorithm.
1818

1919
{% highlight coffeescript %}
20-
shuffle = (a) ->
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]]
28-
# Return the shuffled array.
29-
a
20+
shuffle = (source) ->
21+
# Arrays with < 2 elements do not shuffle well. Instead make it a noop.
22+
return source unless source.length >= 2
23+
# From the end of the list to the beginning, pick element `index`.
24+
for index in [source.length-1..1]
25+
# Choose random element `randomIndex` to the front of `index` to swap with.
26+
randomIndex = Math.floor Math.random() * (index + 1)
27+
# Swap `randomIndex` with `index`, using destructured assignment
28+
[source[index], source[randomIndex]] = [source[randomIndex], source[index]]
29+
source
3030

3131
shuffle([1..9])
3232
# => [ 3, 1, 5, 6, 4, 8, 2, 9, 7 ]

0 commit comments

Comments
 (0)