0

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;
    }
}
Justin Morgan - On strike
  • 30,035
  • 12
  • 80
  • 104
NCFUSN
  • 1,624
  • 4
  • 28
  • 44
  • Are you asking how to remove the `for` loop from the `switch`? – Josh Aug 01 '11 at 20:49
  • 2
    Just a tip: putting "Random question" as the question title is probably not a good idea because it sounds like you're just asking some random question. Something like "how to choose a random case in a switch statement" might have been better. – mgalgs Aug 01 '11 at 22:46

3 Answers3

5

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.

Marvo
  • 17,845
  • 8
  • 50
  • 74
4

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.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
1

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.

Community
  • 1
  • 1
Joe
  • 56,979
  • 9
  • 128
  • 135