I am stuck in one issue regarding to random number. I am generating random number using arc4random()
. I want to generate randome numbers between 0-9 at first. so i am using:
int RandomNumber = arc4random() % 9;
its good. Now suppose I got 8. I don't want my new random number to be 8. So I have done following:
NSMutableArray *aryTemp = [NSMutableArray new];
for (int i = 0; i < [aryTemp Count] < 9; i++) {
int RandomNumber;
do {
RandomNumber = arc4random() % 9;
}
while ([aryTemp containsObject:[NSNumber numberWithInt:RandomNumber]])
[aryTemp addObject:[NSNumber numberWithInt:RandomNumber]];
}
So I am generating a random number than adding it to array than checking for the next random number that is this the previous generated random number or not? If not than add it to the array.
It works fine for few starting numbers but when I left of with few option at that time I have very less chances to generate desire random number and while loop processes takes lots of time due to redundant random number.
What I am looking for I want random numbers of 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 If I got 6 at first time next time the random number must be with in these numbers only 0, 1, 2, 3, 4, 5, 7, 8, 9
Edit: The answer linked in the comments above proposes a more elegant solution - shuffling the array in place, although it uses the same principal as my naive approach :)
If I understand you correctly: You are wanting to select all items from the range 0-9 at random.
My initial approach would be to create a bag with all the items in the range. Each time you randomly select an item - remove it from the bag so you don't select it again.
The following code snippet should achieve this:
try this one
Hope this helps, thanks.
Thank you. Happy coding