0

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 ?

Lorenzo
  • 3,293
  • 4
  • 29
  • 56
Sami
  • 41
  • 2
  • 4
  • 3
    Ignore the computer. How would you do this if you just had a pencil and paper? What steps would you take? – Abizern Oct 14 '15 at 22:12

3 Answers3

7

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
}
Community
  • 1
  • 1
Rob Napier
  • 286,113
  • 34
  • 456
  • 610
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"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • This approach scales poorly as the number of digits gets larger. – Rob Napier Oct 15 '15 at 13:11
  • @RobNapier the OP is asking for a four digits. In my tests here it generates around 90 numbers to extract 45. But there is no bias with 0 first here – Leo Dabus Oct 15 '15 at 13:16
  • Yeah; I can't figure out why it biases towards a leading zero when n is larger. My first calculations on it suggest it shouldn't, but I never seen a non-zero-leading result with n=8 or n=9. – Rob Napier Oct 15 '15 at 13:17
  • 1
    There's no need for the intermediate `Array` BTW. You can build a `Set` from any `SequenceType`. – Rob Napier Oct 15 '15 at 13:18
  • By "n=8 or n=9" I mean "looking for an 8-digit or 9-digit number." A good algorithm here shouldn't be tied to exactly four digits if it can help it. On StackOverflow, people tend to re-use these answers for similar problems that may not be identical. – Rob Napier Oct 15 '15 at 13:19
0

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