Skip to content

Commit

Permalink
Update Shuffle
Browse files Browse the repository at this point in the history
  • Loading branch information
passerbyloo committed Mar 26, 2019
1 parent 6e8b5cd commit b6e9a40
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 0 deletions.
4 changes: 4 additions & 0 deletions Shuffle/README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ public func shuffledArray(_ n: Int) -> [Int] {
var a = [Int](repeating: 0, count: n)
for i in 0..<n {
let j = Int.random(in: 0...i)
// for the Fisher–Yates_shuffle's pseudo code implement in wiki, it will check if i != j
a[i] = a[j]
a[j] = i
}
return a
Expand All @@ -112,6 +114,8 @@ This returns something like `[3, 0, 9, 1, 8, 5, 2, 6, 7, 4]`. As you can see, ev

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!

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.

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.)

## See also
Expand Down
1 change: 1 addition & 0 deletions Shuffle/Shuffle.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public func shuffledArray(_ n: Int) -> [Int] {
var a = Array(repeating: 0, count: n)
for i in 0..<n {
let j = random(i + 1)
a[i] = a[j]
a[j] = i // insert next number from the sequence
}
return a
Expand Down

0 comments on commit b6e9a40

Please sign in to comment.