简体   繁体   中英

How to generate a 4 digit random number with unique digits?

Like: 0123, 0913, 7612
Not like: 0000, 1333, 3499

Can it be done with arcRandom() in swift? Without array or loop?

Or If that impossible, how it be done with arcRandom() in any way ?

You just want to shuffle the digits and pick the number you want.

Start with 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
}
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 Code - For Generation of 4 digit

It gives number between 1000 and 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    
}

Please Note - You can remove this Int(result)! < 1000 if you want numbers like this - 0123, 0913

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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