Search code examples
objective-ccocos2d-iphone

obj-c: generate random number from within range excluding variable two


I am generating a random number between 0 and topOfRange. I can exclude firstNumberToExclude with this code:

NSInteger aRandom;
while ((aRandom = arc4random()%topOfRange) == firstNumberToExclude);

how about if I had two numbers to exclude: firstNumberToExclude and secondNumberToExclude? This was my plan but doesnt seem to be proper:

NSInteger aRandom = arc4random()%topOfRange;
while (aRandom == firstNumberToExclude || aRandom == secondNumberToExclude)
    {
    aRandom = arc4random()%topOfRange;
    }

Solution

  • I think your code would be cleaner, and easier to maintain, if you refactored this into a utility method:

    + (NSInteger)generateRandomExcluding:(NSArray *)exclude topOfRange:(NSInteger)topOfRange {
        NSInteger aRandom = arc4random_uniform(topOfRange);
        while ([exclude containsObject:[NSNumber numberWithInteger:aRandom]]) {
            aRandom = arc4random_uniform(topOfRange);
        }
        return aRandom;
    }
    

    Then you can call it like:

    NSNumber *excludeOne = [NSNumber numberWithInt:5];
    NSNumber *excludeTwo = [NSNumber numberWithInt:13];
    
    NSInteger random = [MyClass generateRandomExcluding:[NSArray arrayWithObjects:excludeOne, excludeTwo, nil] topOfRange:100];