We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
2 parents 42e3340 + 16debf2 commit 291275cCopy full SHA for 291275c
chapters/arrays/shuffling-array-elements.md
@@ -18,12 +18,13 @@ the algorithm.
18
19
{% 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]]
+ if a.length >= 2
+ # From the end of the list to the beginning, pick element `i`.
+ for i in [a.length-1..1]
+ # Choose random element `j` to the front of `i` to swap with.
+ j = Math.floor Math.random() * (i + 1)
+ # Swap `j` with `i`, using destructured assignment
27
+ [a[i], a[j]] = [a[j], a[i]]
28
# Return the shuffled array.
29
a
30
0 commit comments