Make arc4random () not repeat the last number

0

I created a app to generate random numbers.

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

the result was 9

(I execute 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 it to a if , but it did not work.

    
asked by anonymous 05.08.2014 / 03:54

2 answers

1

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

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

arc4random() % number;

Underneath the cloths, the arc4random () does not give the same numerical probability. There is a long discussion about this 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.

In order not to repeat the last one, for security reasons, it is better to draw again if the previous number is the same as the draw.

I hope it helps.

    
14.08.2014 / 17:33
1

Here is a snippet of code that does not allow tens to be repeated. In the example, 6 dozen will be drawn between numbers 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);
    
20.07.2015 / 20:51