產(chǎn)生不重復(fù)的隨機(jī)數(shù)
不考慮復(fù)雜度族淮,簡單粗暴法
struct Random {
/**
* 如區(qū)間表示 ==> [1, end]
*/
static func number(end: Int) -> [Int] {
var startArr = Array(1...end)
var resultArr = Array(count: end, repeatedValue: 0)
for i in 0..<startArr.count {
let currentCount = UInt32(startArr.count - i)
let index = Int(arc4random_uniform(currentCount))
resultArr[i] = startArr[index]
startArr[index] = startArr[Int(currentCount) - 1]
}
return resultArr
}
/**
* 如半閉區(qū)間表示 ==> (start, end]
*/
static func numberPro(start: Int, end: Int) -> [Int] {
let scope = end - start
var startArr = Array(1...scope)
var resultArr = Array(count: scope, repeatedValue: 0)
for i in 0..<startArr.count {
let currentCount = UInt32(startArr.count - i)
let index = Int(arc4random_uniform(currentCount))
resultArr[i] = startArr[index]
startArr[index] = startArr[Int(currentCount) - 1]
}
return resultArr.map { $0 + start }
}
}
let A = Random.number(5)
// = [3, 2, 4, 5, 1]
let Apro = Random.numberPro(10, end: 20)
// = [16, 12, 17, 13, 18, 14, 15, 19, 11, 20]
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者