2

How can I generate random numbers between 0 and 31 without call the number twice in Swift Language ?

Nate Cook
  • 92,417
  • 32
  • 217
  • 178
Fahad
  • 125
  • 1
  • 11

1 Answers1

4

You can create a function that returns a random-number generating closure, like this:

func randomSequenceGenerator(min: Int, max: Int) -> () -> Int {
    var numbers: [Int] = []
    return {
        if numbers.isEmpty {
            numbers = Array(min ... max)
        }

        let index = Int(arc4random_uniform(UInt32(numbers.count)))
        return numbers.remove(at: index)
    }
}

To use it, first call the generator once to create the random sequence generator, then call the return value as many times as you like. This will print out random values between one and six, cycling through all of them before starting over:

let getRandom = randomSequenceGenerator(min: 1, max: 6)
for _ in 1...20 {
    print(getRandom())
}
vacawama
  • 150,663
  • 30
  • 266
  • 294
Nate Cook
  • 92,417
  • 32
  • 217
  • 178
  • http://s17.postimg.org/pz2vbd98v/Screen_Shot_2014_10_20_at_05_26_13.png – Fahad Oct 20 '14 at 02:30
  • http://s17.postimg.org/pz2vbd98v/Screen_Shot_2014_10_20_at_05_26_13.png it does repeat the numbers I want it to be without repetitive . In fact, I have playing cards and I want them appear equally in 4 UIImages without being Duplicated all of them in one array @NateCook – Fahad Oct 20 '14 at 02:39
  • 1
    It's repeating the numbers only because he's calling it more times than there were items in the array. Note, he's generating numbers 1-6 in random order, and when he generates numbers 7-12, again he's generating numbers 1-6 in random order, etc. – Rob Oct 20 '14 at 02:44
  • @Fahad Right, you'd need to modify the numbers in my example for your actual case. (Although looking again, my method doesn't account for the restart - you may a get a repeat after exhausting each sequence of values.) – Nate Cook Oct 20 '14 at 02:46