Skip to content

Commit 7927099

Browse files
committed
Merge branch 'malgorithms-master'
2 parents 42e3340 + 6988fe0 commit 7927099

File tree

1 file changed

+10
-9
lines changed

1 file changed

+10
-9
lines changed

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

+10-9
Original file line numberDiff line numberDiff line change
@@ -17,15 +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-
# 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]]
27-
# Return the shuffled array.
28-
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
2930

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

0 commit comments

Comments
 (0)