1

Hi I'm making an app that would generate random numbers. My question is how do I make it not repeat the same number twice?

Here is my code

int text = rand()  % 5;
switch (text) {
    case 0:
         textView.text = @"1";
        break;
    case 1:
        textView.text = @"2";
        break;
    case 2:
         textView.text = @"3";
        break;
    case 3:
        textView.text = @"4";
        break;
    case 4:
       textView.text = @"5";
        break;
    default:
        break;

}

Thank you for your help!

Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200
  • possible duplicate of [Generating non-repeating random numbers](http://stackoverflow.com/questions/8554292/generating-non-repeating-random-numbers) – jscs Jul 19 '14 at 19:18
  • @JoshCaswell There's a difference: The question you linked asks for a permutation (never repeating values). This one is about not repeating a value twice in a row. – Nikolai Ruhe Jul 20 '14 at 04:03

2 Answers2

2

Compare your new random value against your current value. In case it's similar just create a new random value until it's different:

int text = rand()  % 5;
while (text == [textView.text intValue]) {
    text = rand()  % 5;
}
switch (text) {
    case 0:
         textView.text = @"1";
        break;
    case 1:
        textView.text = @"2";
        break;
    case 2:
         textView.text = @"3";
        break;
    case 3:
        textView.text = @"4";
        break;
    case 4:
       textView.text = @"5";
        break;
    default:
        break;
}

Also, it is more elegant with a do-while-loop. Just exchange the part before switch with:

int text;
do {
    text = rand() % 5;
} while (text == [textViewtext intValue]);
Jens Wirth
  • 17,110
  • 4
  • 30
  • 33
0

When selecting a new value you are really not drawing out of five but only four possibilities: The old value is forbidden.

So do that and adjust the result to always leave out the old value:

// get the current value
int oldNumber = [textView.text intValue] - 1;

// pick a new value
int randomNumber = rand() % 4;

// adjust new value to avoid the old value
if (randomNumber >= oldNumber)
    randomNumber += 1;

// set the new value on the textView
textView.text = [@(randomNumber + 1) stringValue];
Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200