繁体   English   中英

如何生成具有唯一数字的4位随机数?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM