简体   繁体   中英

How to randomly generate integers between 0 to 3 without making them consecutive in Java?

So far I have managed to generate random numbers using Random.

for(int i=0; i<10; i++){
    prevnum = num;
    num = random.nextInt(4);
    num = num==prevnum?ran.nextInt(4):num;
    System.out.println("random number: " + num);
}

I do not want consecutive repeats, what should I do?

EDIT/SOLUTION:

I solved the issue using this workaround.

By checking if it was running for the first time to avoid nullpointerexception.

And the just used an ArrayList to remove any chances of repitition by removing the previous randomly generated number from the small pool/range.

public void printRandom(){
        for(int i=0; i<10; i++){
            if(firstrun){
                firstrun=false;
                num = random.nextInt(4);
                System.out.println(num);
            } else{
                num = getRandom(num);
                System.out.println(num);
            }
        }
    }

    int getRandom(int prevNum){
         ArrayList choices = new ArrayList(Arrays.asList(0, 1, 2, 3));
         choices.remove(prevNum);
         return (int) choices.get(random.nextInt(3));
    }

You better to get a random number until it would be different with the last number, not just once, in other words repeat this condition:

num = num==prevnum?ran.nextInt(4):num;

like:

do {
    num = num==prevnum?ran.nextInt(4):num;
while (num != prevnum);

because your numbers are few, they might be the same, so check it more than once if it is needed.

Try this

Random ran = new Random();
int cur, pre = ran.nextInt(4);
for (int i = 0; i < 10; i++) {
    cur = ran.nextInt(4);
    while (cur == pre) {
        cur = ran.nextInt(4);
    }
    pre = cur;
    System.out.println(cur);
}

If you do not want a consecutive repeat, then you always want the gap between two consecutive numbers to be non-zero. That you suggests you pick your first number normally, and from that point on you pick a random, but non-zero, gap. Add the gap to the previous number to get the next number, which will always be different.

Some pseudocode:

// First random number.
currentNum <- random(4);
print(currentNum);

// The rest of the random numbers.  
repeat
  gap <- 1 + random(3);
  currentNum <- (currentNum + gap) MOD 4;
  print(currentNum);
until enough numbers;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM