Search code examples
iphonerandomsdkarc4random

Use once on arc4random() number


How you code arc4random() that does not repeat number twice?

For instance. I'm using switch and button. I don't want to generate reused the same arc4random number again. If I have arc4random that generation numbers 2,4,42,32,42... I don't want to 42 to appear again.

How do I avoid this?

  switch (arc4random() % 50 )
        {
            case 1:
                text.text = @"You are silly boy";
                break;
            case 2:
                text.text = @"Well, you very very silly"];
                break;
            case 3:
                text.text = @"stop being silly"];
                break;
            case 4:
                [text.text = @"silly... silly"];
                break;
            case 5:
                text.text = @"what you silly boy"];
                break;

           ...
            case 0:
                text.text = @"you silly"];
                break;
        }

Solution

  • One way of doing it would be as follows:

    static int maxNumOfCases = 50; //This could be any number of cases that you need in your app.
    
    ......
    
    switch (arc4random() % (maxNumOfCases--)) {
                case 1:
                    text.text = @"You are silly boy";
                    break;
                case 2:
                    text.text = @"Well, you very very silly"];
                    break;
                case 3:
                    text.text = @"stop being silly"];
                    break;
                case 4:
                    [text.text = @"silly... silly"];
                    break;
                case 5:
                    text.text = @"what you silly boy"];
                    break;
                    ...
                case 0:
                text.text = @"you silly"];
                break;
    }
    

    This code always switches to a unique case on each invocation. The way the code works is by decreasing the range of arc4random() at each invocation by 1.

    Update: Keep note that this method biases more towards the end of the run to a smaller range of numbers. So this is not a true non-repeating random number generation. But if thats not a concern, its an easy one liner to include in your code.