[英]How to generate a 4 digit random number with unique digits?
像: 0123, 0913, 7612
不喜歡: 0000, 1333, 3499
可以用arcRandom()
快速完成嗎? 沒有數組或循環?
或者,如果那不可能,怎么用arcRandom()
完成呢?
您只需要隨機排列數字並選擇所需的數字。
從Nate Cook的Fischer-Yates隨機代碼開始 。
// Start with the digits
let digits = 0...9
// Shuffle them
let shuffledDigits = digits.shuffle()
// Take the number of digits you would like
let fourDigits = shuffledDigits.prefix(4)
// Add them up with place values
let value = fourDigits.reduce(0) {
$0*10 + $1
}
var fourUniqueDigits: String {
var result = ""
repeat {
// create a string with up to 4 leading zeros with a random number 0...9999
result = String(format:"%04d", arc4random_uniform(10000) )
// generate another random number if the set of characters count is less than four
} while Set<Character>(result.characters).count < 4
return result // ran 5 times
}
fourUniqueDigits // "3501"
fourUniqueDigits // "8095"
fourUniqueDigits // "9054"
fourUniqueDigits // "4728"
fourUniqueDigits // "0856"
Swift代碼 -用於生成4位數
它給出的數字在1000到9999之間。
func random() -> String {
var result = ""
repeat {
result = String(format:"%04d", arc4random_uniform(10000) )
} while result.count < 4 || Int(result)! < 1000
print(result)
return result
}
請注意 -您可以刪除此Int(結果)! <1000,如果您想要這樣的數字-0123,0913
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.