Skip to content

Commit b6e9a40

Browse files
committed
Update Shuffle
1 parent 6e8b5cd commit b6e9a40

File tree

2 files changed

+5
-0
lines changed

2 files changed

+5
-0
lines changed

Shuffle/README.markdown

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,8 @@ public func shuffledArray(_ n: Int) -> [Int] {
9696
var a = [Int](repeating: 0, count: n)
9797
for i in 0..<n {
9898
let j = Int.random(in: 0...i)
99+
// for the Fisher–Yates_shuffle's pseudo code implement in wiki, it will check if i != j
100+
a[i] = a[j]
99101
a[j] = i
100102
}
101103
return a
@@ -112,6 +114,8 @@ This returns something like `[3, 0, 9, 1, 8, 5, 2, 6, 7, 4]`. As you can see, ev
112114

113115
The `shuffledArray()` function first creates a new array with `n` zeros. Then it loops `n` times and in each step adds the next number from the sequence to a random position in the array. The trick is to make sure that none of these numbers gets overwritten with the next one, so it moves the previous number out of the way first!
114116

117+
For this function, `The condition that checks if j ≠ i may be omitted in languages that have no problems accessing uninitialized array values, and for which assigning is cheaper than comparing.`, you can check it in wiki. And also remove checking logic will optimise performance.
118+
115119
The algoritm is quite clever and I suggest you walk through an example yourself, either on paper or in the playground. (Hint: Again it splits the array into two regions.)
116120

117121
## See also

Shuffle/Shuffle.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ public func shuffledArray(_ n: Int) -> [Int] {
3030
var a = Array(repeating: 0, count: n)
3131
for i in 0..<n {
3232
let j = random(i + 1)
33+
a[i] = a[j]
3334
a[j] = i // insert next number from the sequence
3435
}
3536
return a

0 commit comments

Comments
 (0)