I've a problem with the generation of random values with arc4random in Xcode. I want to exclude from the random generation those number that are already picked up. This is the algorithm that I've wroten
int randomValue = (arc4random() % numberofquest)+ 1;
int kk=1;
if (kk==1) {
//first time add the first random value
[oldquest addObject: randomValue];
}
else {
//control if the number is already in the vector
for (int j=1; j<[oldquest count]; j++)
{
if (randomValue==oldquest[j])
{
randomValue = (arc4random() % numerodomande)+ 1;
}
else
{
[oldquest addObject: randomValue];
}
}
}
kk=kk+1
But It doesn't work. I suppose maybe because randomvalue and the j-th object in the array are not comparable (int the first and string the second?). Can anyone help me please?
I'm sorry, Ares answer was almost right. You can compare two different NSNumber objects.
Here is my solution:
- (int) generateRandomNumber {
int number = arc4random() % 100;
if ([chosen_numbers indexOfObject:[NSNumber numberWithInt:number]]!=NSNotFound)
number = [self generateRandomNumber];
[chosen_numbers addObject:[NSNumber numberWithInt:number]];
return number;
}
Since Alessandro has some trouble implementing it heres an example inside a UIViewController class. This works for 100 numbers:
#import "ViewController.h"
@implementation ViewController {
NSMutableArray * chosen_numbers;
}
- (void)viewDidLoad
{
[super viewDidLoad];
chosen_numbers = [[NSMutableArray alloc] init];
for(int i = 0; i<90; i++) {
NSLog(@"number: %d",[self generateRandomNumber]);
}
}
- (int) generateRandomNumber {
int number = arc4random() % 100;
if ([chosen_numbers indexOfObject:[NSNumber numberWithInt:number]]!=NSNotFound)
number = [self generateRandomNumber];
[chosen_numbers addObject:[NSNumber numberWithInt:number]];
return number;
}
@end