views:

166

answers:

3

How can you disallow some nubers from being chosen with the arc4random function?

Current code:

int random = (arc4random() % 92);

(numbers from 0 to 92)

I want it do disallow the following numbers: 31, 70, 91, 92

Thank you (:

+3  A: 

First, you'll need to change

% 92

to

% 93

to get numbers from 0..92

I'd do something like this

int random;

do {
    random = arc4random() % 93;
}
while ( random == 31 || random == 70 || random == 91 || random == 92 );
Bob Kaufman
Ah, sorry, the original code was counting an array, and I knew how many objects the array had, so I just wrote that instead :)Help me understand the code; basically what it does is getting a random number, and if the number is any of the ones, get a new? thanks (:
Emil
@Emil - correct. If it's one of the disallowed values, just call the method again.
Bob Kaufman
Great! :) Thank you, the code is working :)
Emil
+1  A: 

Simple, keep asking for numbers:

get a new random number
while the new number is one of the disallowed ones:
    get a new random number
return the random number

Pseudo code, but you should get the idea.

St3fan
Yep, got it. :)
Emil
+3  A: 

If you are going to disallow numbers 91 and 92, why bother including them in your mod?

Expanding on the previous answer:

int random;
do {
    random = arc4random() % 91;
}
while ( random == 31 || random == 70 );
harwig
@harwig - I was thinking about this, too. However leaving them in, although less efficient from a coding and execution standpoint, serves to document the fact that we're explicitly excluding these values, just in case somebody decides to change the modulus a few years from now.
Bob Kaufman
@Bob Kaufman - very good point, as I'm sure that could be a potential cause of major headaches in the future.
harwig