You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: Shuffle/README.markdown
+2-6
Original file line number
Diff line number
Diff line change
@@ -33,8 +33,6 @@ You should see three different arrangements -- or [permutations](../Combinatoric
33
33
34
34
This shuffle works *in place*, it modifies the contents of the original array. The algorithm works by creating a new array, `temp`, that is initially empty. Then we randomly choose an element from the original array and append it to `temp`, until the original array is empty. Finally, the temporary array is copied back into the original one.
35
35
36
-
> **Note:**`random()` is a helper function that returns a random integer between 0 and the given maximum.
37
-
38
36
This code works just fine but it's not very efficient. Removing an element from an array is an **O(n)** operation and we perform this **n** times, making the total algorithm **O(n^2)**. We can do better!
39
37
40
38
## The Fisher-Yates / Knuth shuffle
@@ -45,7 +43,7 @@ Here is a much improved version of the shuffle algorithm:
45
43
extensionArray {
46
44
publicmutatingfuncshuffle() {
47
45
for i instride(from: count -1, through: 1, by: -1) {
48
-
let j =random(i +1)
46
+
let j =Int.random(in: 0...i)
49
47
if i != j {
50
48
swap(&self[i], &self[j])
51
49
}
@@ -56,8 +54,6 @@ extension Array {
56
54
57
55
Again, this picks objects at random. In the naive version we placed those objects into a new temporary array so we could keep track of which objects were already shuffled and which still remained to be done. In this improved algorithm, however, we'll move the shuffled objects to the end of the original array.
58
56
59
-
> **Note**: When you write `random(x)`, the largest number it will return is `x - 1`. We want to have `j <= i`, not `j < i`, so the largest number from the random number generator needs to be `i`, not `i - 1`. That's why we do `random(i + 1)`. If we didn't add that 1 to compensate, it would make some shuffle orders more likely to occur than others.
60
-
61
57
Let's walk through the example. We have the array:
0 commit comments