Skip to content

Commit 291275c

Browse files
committed
Merge git://github.com/malgorithms/coffeescript-cookbook.github.com into malgorithms-master
2 parents 42e3340 + 16debf2 commit 291275c

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

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

+7-6
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)