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

问题描述 投票:-2回答:3

喜欢:0123, 0913, 7612 不喜欢:0000, 1333, 3499

可以用快速的arcRandom()完成吗?没有数组或循环?

或者,如果这不可能,以任何方式如何使用arcRandom()

ios swift
3个回答
4
投票

你只想将数字随机抽取并选择你想要的数字。

Nate Cook's Fischer-Yates shuffle code开始。

// 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
}

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"

0
投票

Swift Code - 用于生成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

© www.soinside.com 2019 - 2024. All rights reserved.