Are you a new iPhone developer or
Objective-C programmer?Need a quick and easy way to generate a
random number between a set range of numbers?
This code saves a
lot of time and effort used in generating random
numbers.
arc4random() gets
a random floating point number(between 0 and 1) but how do I keep it
in a specific range?
----------------------------------------------------------------------------------------------------
Random Integer:
----------------------------------------------------------------------------------------------------
-(int)randomIntegerBetween:(int)num1
andLargerInteger:(int)num2
{
return (arc4random()%((num2-num1)+1)) + num1;
}
----------------------------------------------------------------------------------------------------
For
example... [self randomIntegerBetween:5
andLargerInteger:8];
Could return... 5, 6, 7, or
8.
----------------------------------------------------------------------------------------------------
Random Float:
----------------------------------------------------------------------------------------------------
-(float)randomFloatBetween:(float)num1
andLargerFloat:(float)num2
{
int startVal =
num1*10000;
int endVal = num2*10000;
int randomValue = startVal + (arc4random() %
(endVal - startVal));
float a =
randomValue;
return (a /
10000.0);
}
----------------------------------------------------------------------------------------------------
For example... [self
randomFloatBetween:5.5 andLargerInteger:8.8];
Could
return... 5.5, 5.5681, 6.183, 7.8890, or 8.8 - and much
more
NOTE:
This method can be toyed with. It works
the same as the integer generator, but converts the integer into a
float at the end. This gives you control over how many decimal
places you would like. For example, 10000 will return a float with 4
decimal places .xxxx.
The number of 0's will determine the amount of decimal places.