0

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

0

4 Answers 4

10

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 ); 
Sign up to request clarification or add additional context in comments.

3 Comments

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 - correct. If it's one of the disallowed values, just call the method again.
Theoretically your code could run endlessly, which is bad way to go. Instead, you should create an array with all possible numbers (and leave out those you want to exclude), then use random to retrieve via index a random array entry.
4

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 ); 

2 Comments

@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 - very good point, as I'm sure that could be a potential cause of major headaches in the future.
2

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.

Comments

0

Solution for Swift:

func randomValue(except: Int) -> Int { var rand: Int = 0; repeat { rand = Int(arc4random_uniform(3) + 1) } while(rand == except) return Int(rand) } 

1 Comment

Thanks, that works for one exception, but not for a list of exceptions! :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.