forked from kelvinlauKL/swift-algorithm-club
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShuffle.swift
More file actions
32 lines (30 loc) · 706 Bytes
/
Shuffle.swift
File metadata and controls
32 lines (30 loc) · 706 Bytes
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
import Foundation
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 (count - 1).stride(through: 1, by: -1) {
let j = random(i + 1)
if i != j {
swap(&self[i], &self[j])
}
}
}
}
/*
Simultaneously initializes an array with the values 0...n-1 and shuffles it.
*/
public func shuffledArray(n: Int) -> [Int] {
var a = [Int](count: n, repeatedValue: 0)
for i in 0..<n {
let j = random(i + 1)
if i != j {
a[i] = a[j]
}
a[j] = i // insert next number from the sequence
}
return a
}