Make arc4random() not repeat last number

Asked

Viewed 171 times

0

I created a app to generate random numbers.

Only I wanted him not to repeat the last number he showed. Example:

the result was 9

(run the method that generates the random number again)

the result was 9.

I tried to create a variable that stores the value of the last number random and then compare in a if, but it didn’t work.

  • 1

    According to Apple’s documentation, arc4random generates random numbers uniformly and should not generate repeated numbers. Add the code where the function is being called, so it will be easier to find out what the problem is.

2 answers

1


The problem with arc4random() is that it does not generate the numbers with the same probability.

I imagine you must be using arc4random() this way:

arc4random() % number;

Beneath the cloths, arco4random() does not give the same numerical probability. There is a long discussion about it but nothing like looking at the documentation to understand the essentials:

 arc4random_uniform() will return a uniformly distributed random number less than upper_bound.
 arc4random_uniform() is recommended over constructions like ``arc4random() % upper_bound'' as it avoids
 "modulo bias" when the upper bound is not a power of two.

That is, if you use arc4random_uniform, you have a better distribution.

Already not to repeat the last, for safety, it is better to draw again if the previous number is equal to the drawn.

I hope it helps.

1

It follows code that does not allow dozens to be repeated. In the example, 6 tens will be drawn between the number 1 and 60.

NSMutableArray * arrayNumbers = [NSMutableArray new];

while (YES) {
    int randomNumber = arc4random() % 60;
    BOOL foundNumber = NO;
    for (int j = 0; j < arrayNumbers.count; j++) {
        if ([[arrayNumbers objectAtIndex:j] intValue] == randomNumber) {
            foundNumber = YES;
            break;
        }
    }
    if (!foundNumber) {
        [arrayNumbers addObject:[NSString stringWithFormat:@"%i", randomNumber]];
        if (arrayNumbers.count == 6) {
            break;
        }
    }
}

NSLog(@"%@", arrayNumbers);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.