Fisher- Yates shuffle在運算隨機排列的通用algorithm 。
-- To shuffle an array a of n elements (indices 0..n-1):
for i from n−1 downto 1 do
j ← random integer such that 0 ≤ j ≤ i
exchange a[j] and a[i]
An equivalent version which shuffles the array in the opposite direction (from lowest index to highest) is:
-- To shuffle an array a of n elements (indices 0..n-1):
for i from 0 to n−2 do
j ← random integer such that i ≤ j < n
exchange a[i] and a[j]
運用extension 的方式 加入func shuffle()(注意:前方必須加mutating)
swift 4 程式碼:
extension Array {
/// shuffles contents of array
mutating func shuffle(){
guard count > 1 else {return}
for i in indices.dropLast(){
let diff = distance(from: i, to: endIndex)
let j = index(i, offsetBy: diff.arc4random)
swapAt(i,j)
}
}
}
extension Int {
var arc4random : Int {
if self > 0 {
return Int(arc4random_uniform(UInt32(self)))
}else if self < 0 {
return -Int(arc4random_uniform(UInt32(abs(self))))
}else {
return 0
}
}
}
acr4random_uniform(max)
max需為UInt32,生成隨機數範圍 0..
加入extension後使用起來很簡單
shuffle 範例:
var x = [1,2,3,4,5,6,7]
x.shuffle()
acr4random 範例:
let y = 30
y.arc4random