[英]How to generate a random number in Swift without repeating the previous random number?
我對 Swift 和編程邏輯很陌生,所以請耐心等待
如何在不重復上次生成的數字的情況下,在 Swift 中生成 0 到 9 之間的隨機數? 因為同一個數字不會連續出現兩次。
我的解決方案,我認為它很容易理解
var nums = [0,1,2,3,4,5,6,7,8,9]
while nums.count > 0 {
// random key from array
let arrayKey = Int(arc4random_uniform(UInt32(nums.count)))
// your random number
let randNum = nums[arrayKey]
// make sure the number isnt repeated
nums.swapAt(arrayKey, nums.count-1)
nums.removeLast()
}
將之前生成的數字存儲在變量中,並將生成的數字與之前的數字進行比較。 如果它們匹配生成一個新的隨機數。 重復生成新數字,直到它們不匹配。
var previousNumber: UInt32? // used in randomNumber()
func randomNumber() -> UInt32 {
var randomNumber = arc4random_uniform(10)
while previousNumber == randomNumber {
randomNumber = arc4random_uniform(10)
}
previousNumber = randomNumber
return randomNumber
}
Swift 5 更新
這是一個很好的技巧,可以從之前選擇的數字中平等地選擇。
您有 10 個號碼,但您只想從 9 個號碼中進行選擇(0 到 9,但不包括前一個號碼)。 如果將范圍減少 1,則可以從 9 個隨機數中進行選擇,然后將重復的數字替換為范圍的前一個頂部數字。 這樣,您每次只需生成一個隨機數即可獲得一致性。
這可以實現為Int.random(in:excluding:)
在其中傳遞要exclude
的值。
extension Int {
static func random(in range: ClosedRange<Int>, excluding x: Int) -> Int {
if range.contains(x) {
let r = Int.random(in: Range(uncheckedBounds: (range.lowerBound, range.upperBound)))
return r == x ? range.upperBound : r
} else {
return Int.random(in: range)
}
}
}
例子:
// Generate 30 numbers in the range 1...3 without repeating the
// previous number
var r = Int.random(in: 1...3)
for _ in 1...30 {
r = Int.random(in: 1...3, excluding: r)
print(r, terminator: " ")
}
print()
1 3 2 1 2 1 3 2 1 3 1 3 2 3 1 2 3 2 1 3 2 1 3 1 2 3 2 1 2 1 3 2 3 2 1 3 1 2 1 2
上一個答案:
var previousNumber = arc4random_uniform(10) // seed the previous number
func randomNumber() -> UInt32 {
var randomNumber = arc4random_uniform(9) // generate 0...8
if randomNumber == previousNumber {
randomNumber = 9
}
previousNumber = randomNumber
return randomNumber
}
最簡單的方法是使用 repeat/while:
let current = ...
var next: Int
repeat {
next = Int(arc4random_uniform(9))
} while current == next
// Use `next`
將你想要的所有值放入一個數組中,使用 arc4random_uniform(SIZEOFARRAY) 生成一個隨機數並從數組中拉出隨機值的索引,然后重復這個過程直到數組為空。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.