NCFUSN
NCFUSN

Reputation: 1654

How to choose a random case in a switch statement

I want to output several questions, but in a random order. How can I ask all questions randomly without repeating one?

for(int i=0; i<4; i++)
{
    int question=rand()%4;
    switch(question)
    {
        case 0:
            NSLog(@"What is your name");
            break;
        case 1:
            NSLog(@"Who are you");
            break;
        case 2:
            NSLog(@"What is your name");
            break;
        case 3:
            NSLog(@"How do you do");
            break;
        case 4:
            NSLog(@"Are you?");
            break;
    }
}

Upvotes: 0

Views: 5410

Answers (3)

Marvo
Marvo

Reputation: 18143

Keep the questions in an array. Shuffle the array at the start of questioning. Now pull one question from the list per iteration, ask it, get the answer, and continue until you run out of questions.

Upvotes: 5

Carl Norum
Carl Norum

Reputation: 225142

rand(3) is pretty famous for having poor implementations that have pretty short cycles for the lower bits. Try using different bits, or use random(3) instead. In fact, the rand(3) man page on OS X says:

These interfaces are obsoleted by random(3).

Also - % 4 can never be larger than 3, so your case 4 will never execute in this program.

Upvotes: 4

Joe
Joe

Reputation: 57179

It is recommended to use arc4random() for a better algorithm with out the need to seed. Otherwise call srand to seed your call to rand.

Upvotes: 1

Related Questions