How can I create a random number between two random numbers that come from user input variables in swift using arc4random().
Asked
Active
Viewed 330 times
-3
-
1There are so many answers on this site already for finding a random number between two numbers. – michaelsnowden Oct 15 '14 at 01:20
-
possible duplicate of [How does one generate a random number in Apple's Swift language?](http://stackoverflow.com/questions/24007129/how-does-one-generate-a-random-number-in-apples-swift-language) – Kampai Oct 15 '14 at 06:10
1 Answers
0
A simple way that is easy to understand/implement is to:
- Subtract the two numbers
- Find a random number on this difference - 1
- Add the random number back to the lower of the original two numbers to get a number in between the two.
for example:
let a: UInt32 = 1
let b: UInt32 = 8
let c = b - a - 1
let newRandomNumber = 1 + arc4random_uniform(c)
I'll let you work our what to do if b is the smaller number.

Steve Rosenberg
- 19,348
- 7
- 46
- 53