How can I generate random numbers between 0 and 31 without call the number twice in Swift Language ?
Asked
Active
Viewed 5,652 times
2
-
What does it mean to "call the number"? – recursive Oct 20 '14 at 02:15
-
I mean if the random number was 5 , it doesn't repeat 5 again in the method – Fahad Oct 20 '14 at 02:16
-
looks like a duplicate of http://stackoverflow.com/questions/196017/unique-non-repeating-random-numbers-in-o1 – Lance Oct 20 '14 at 02:31
1 Answers
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())
}
-
-
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
-
1It'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