How to compare an array of numbers and make sure none of the values are the same?

141 views Asked by At

I am randomly generating 6 numbers using

self.number1 = [[NSNumber alloc] initWithInt:((arc4random() % 
                (hightestNumber-lowestNumber+1)) + lowestNumber)];

I do that for all six numbers, but some of the numbers come out the same. What code can I use to make sure that not any two or more numbers are the same value. I was going to use an if statement to compare the number to all six numbers and then call the arc4random code again but there is a possibility of it coming out the same value of another number again and I would have to test it again after. I really am stumped on this one. Thank you for your help.

2

There are 2 answers

3
Caleb On BEST ANSWER

What code can I use to make sure that not any two or more numbers are the same value.

A set doesn't have duplicate values, so one option is to add numbers to a set until the size of the set reaches the number of objects you want (6, in your case).

NSMutableSet *set = [NSMutableSet set];
while ([set count] < 6) {
    [set addObject:@((arc4random() % (hightestNumber-lowestNumber+1)) + lowestNumber)];
}

Another option is to pick numbers from an existing list, removing each one you choose:

NSArray *list = @[@5, @6, @7, @8, @9, @10, @11, @12, @13];
NSMutableArray *sourceList = [list mutableCopy];
NSMutableArray *finalList = [NSMutableArray array];
for (int i = 0; i < 6; i++) {
    // (omitting code to choose a random index for brevity)
    [finalList addObject:[sourceList objectAtIndex:randomIndex]];
    [sourceList removeObjectAtIndex:randomIndex];
}

This method can work well if the list you're choosing from contains consecutive (or at least monotonically increasing) numbers, since that makes it easy to guarantee that the values in the source list are unique.

0
pjs On

In addition to Caleb's excellent suggestions, if the range is relatively small you can create an array with all the values enumerated, shuffle them, and then pick the first 6.