is there any simple tutorial or help available to getting to learn how to use arc4random to select a random set of numbers?
A:
If each number in the set of numbers you need has to be within a specific range, you normally do that using, in this order: arc4random(), modulus, multiplication, addition.
For example, to generate 10 even numbers in the range [6, 90): You will ultimately be adding 6, the lowest value in the range. Your multiplier is 2 because you want every second number (every even number == every second number). The denominator of your modulus will be (the width of the range == 90-6 == 84) / (your multiplier == 2) == 42.
So your code would look like:
int const kHowManyNumbersToHaveInTheSet = 10;
int const kLowerBoundInclusive = 6;
int const kUpperBoundExclusive = 90;
int const kIntervalBetweenAcceptableValues = 2;
int rangeWidth = kUpperBoundExclusive - kLowerBoundInclusive;
int denominatorForModulus = rangeWidth / kIntervalBetweenAcceptableValues;
NSMutableSet *mySet = [NSMutableSet setWithCapacity: kHowManyNumbersToHaveInTheSet];
while (mySet.count < kHowManyNumbersToHaveInTheSet)
{
int newNumber = arc4random();
newNumber %= denominatorForModulus;
newNumber *= kIntervalBetweenAcceptableValues;
newNumber += kLowerBoundInclusive;
[mySet addObject: [NSNumber numberWithInt: newNumber]];
}
Jon Rodriguez
2010-09-14 20:29:13
Note that I took you to mean "set" in the mathematical sense (that no value can be duplicated). If you do want values to be able to be repeated, you should use an array, not a set, but otherwise the code is the same.
Jon Rodriguez
2010-09-14 20:35:33
i had a different idea in mind i wanted to use this line questionNumber = questionNumber + 1;to be able to have the questionNumber appear randomly from all of the rest.
Alx
2010-09-15 18:48:31
I'm sorry, but your comment is too vague for me to understand what you are trying to do. Are you saying that you want to select a random integer from between a minimum and a maximum and ensure that the new number has not already been selected?
Jon Rodriguez
2010-09-16 01:46:58