Skip to content

Commit fc7869c

Browse files
authored
Merge pull request kodecocodes#869 from passerbyloo/master
Update Shuffle to remove unneeded check
2 parents 6f4775d + b6e9a40 commit fc7869c

File tree

2 files changed

+5
-6
lines changed

2 files changed

+5
-6
lines changed

Shuffle/README.markdown

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -96,9 +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-
if i != j {
100-
a[i] = a[j]
101-
}
99+
// for the Fisher–Yates_shuffle's pseudo code implement in wiki, it will check if i != j
100+
a[i] = a[j]
102101
a[j] = i
103102
}
104103
return a
@@ -115,6 +114,8 @@ This returns something like `[3, 0, 9, 1, 8, 5, 2, 6, 7, 4]`. As you can see, ev
115114

116115
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!
117116

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+
118119
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.)
119120

120121
## See also

Shuffle/Shuffle.swift

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +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-
if i != j {
34-
a[i] = a[j]
35-
}
33+
a[i] = a[j]
3634
a[j] = i // insert next number from the sequence
3735
}
3836
return a

0 commit comments

Comments
 (0)