Possible Duplicates:
Generating random numbers in Objective-C
iOS Random Numbers in a range
Generate non-repeating, no sequential numbers
I am looking for method that give me random numbers between two numbers, and the first number will be number that I choose between the numbers.
for example, if I give this random function 5 and 10 and 9 as the first number, so it will give me: 9,10,7,6,5,8
I tried to use it:
NSUInteger count = [array count];
for (NSUInteger i = 1; i < count; ++i) {
int nElements = count - i;
int n = (random() % nElements) + i;
while (n==`firstnumber`) {
n = (random() % nElements) + i;
}
}
It looks like you are after a shuffling algorithm. The following category on
NSMutableArraywill do the job:Your requirement is that the number in the first position of the array is fixed (given by you). Then, you can do something like this:
Populate the array with all numbers between
minValueandmaxValue(both included) except forfirstValue.Shuffle the array.
Insert
firstValueat the first position in the array.Resulting in the following code: