Skip to content

Commit 6e8b5cd

Browse files
committed
Update Shuffle
according to https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle `checks if j ≠ i may be omitted`, and also remove checking logic will optimise performance(tested by 100000 times random).
1 parent ea0fd54 commit 6e8b5cd

File tree

2 files changed

+0
-6
lines changed

2 files changed

+0
-6
lines changed

Shuffle/README.markdown

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -96,9 +96,6 @@ 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-
}
10299
a[j] = i
103100
}
104101
return a

Shuffle/Shuffle.swift

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,6 @@ 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-
}
3633
a[j] = i // insert next number from the sequence
3734
}
3835
return a

0 commit comments

Comments
 (0)