Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generating random numbers without consecutive repetition

How can I generate random integers from 0 - 4 in such a way that the same number is not generated twice consecutively? For example, if 3 is the number that is generated the first time then 0,1,2,4 will be the possible numbers for random generation the second time. If 2 is generated the second time then 0,1,3,4 will be the possible numbers for random generation the third time and so on.

like image 900
oopology Avatar asked Mar 31 '13 20:03

oopology


People also ask

How do you generate random numbers within range without repetition in Python?

import numpy as np; np. random. permutation(100)[:10] also generates 10 numbers selected from 0 to 99, without duplicates.

Can you generate the same random numbers everytime?

random seed() example to generate the same random number every time. If you want to generate the same number every time, you need to pass the same seed value before calling any other random module function.


2 Answers

int oldrand = <prior random number>;
int adder = randomNumberGenerator() % 4;
int newrand = (oldrand + adder + 1) % 5;
like image 91
Hot Licks Avatar answered Oct 15 '22 10:10

Hot Licks


uint32_t myRandomNumber(uint32_t upperBound, uint32_t avoid) {
    if (avoid < upperBound) {
        --upperBound;
    }
    uint32_t number = arc4random_uniform(upperBound);
    if (number >= avoid) {
        ++number;
    }
    return number;
}

Call it like this the first time:

uint32_t number = myRandomNumber(5, 5);

Call it like this after the first time:

number = myRandomNumber(5, number);
like image 32
rob mayoff Avatar answered Oct 15 '22 09:10

rob mayoff