forked from kodecocodes/swift-algorithm-club
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Shuffle.swift
38 lines (34 loc) · 837 Bytes
/
Shuffle.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import Foundation
/* Returns a random integer between 0 and n-1. */
public func random(_ n: Int) -> Int {
return Int(arc4random_uniform(UInt32(n)))
}
extension Array {
/*
Randomly shuffles the array in-place
This is the Fisher-Yates algorithm, also known as the Knuth shuffle.
Time complexity: O(n)
*/
public mutating func shuffle() {
for i in (1...count-1).reversed() {
let j = random(i + 1)
if i != j {
let t = self[i]
self[i] = self[j]
self[j] = t
}
}
}
}
/*
Simultaneously initializes an array with the values 0...n-1 and shuffles it.
*/
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
}