ConfidentKeyboard
ConfidentKeyboard

Reputation: 23

How to generate a random number without a repeat in Java

I am using this to generate a random number inside a method and return it:

int randomValue = ThreadLocalRandom.current().nextInt(0, filteredArrayList.size());

How can I make sure there are not two random numbers in a row? I don't care if I get a 3, then a 5, then a 3 again. Only if I get a 3 and then a 3.

Upvotes: 1

Views: 1350

Answers (5)

LucasL
LucasL

Reputation: 121

Edited: I'd do something like this: (requires the last random value/a non-reachable number for the first time, e.g. -1)

private int notPreviousRandom(int previousRandomValue) {
    int randomValue;
    do {
        randomValue = ThreadLocalRandom.current().nextInt(0, filteredArrayList.size());
    } while (randomValue == previousRandomValue);

    return randomValue;
}

Alternatively you could define previousRandomValue as an attribute:

// class
private int previousRandomValue = -1;
// ...

private int notPreviousRandom() {
    int randomValue;
    do {
        randomValue = ThreadLocalRandom.current().nextInt(0, filteredArrayList.size());
    } while (randomValue == previousRandomValue);
    previousRandomValue = randomValue; // for the next time you're using the
                                        // method
    return randomValue;
}

Upvotes: 0

11thdimension
11thdimension

Reputation: 10633

Try following sample

import java.util.Random;


public class RandomTest {
    public static void main(String[] args) {
        for(int i = 0; i < 10; i++) {
            System.out.println("####### " + RandomUtil.getRandomInt(10));
        }
    }
}

class RandomUtil {
    private static int lastInt = -1;
    private static Random random = new Random();

    public synchronized static int getRandomInt(int upperBound) {
        return getRandomInt(0, upperBound);
    }

    public synchronized static int getRandomInt(int lowerBound, int upperBound) {
        int newInt = -1;

        while( (newInt = lowerBound + random.nextInt(upperBound - lowerBound)) == lastInt) {
            //Keep looping
        }

        lastInt = newInt;

        return newInt;
    }
}

Upvotes: 1

msagala25
msagala25

Reputation: 1806

    int temp = -1; // This will be your value to be compared to random value
    for(int i = 0; i < 10; i++) { // assuming your filteredArraylist is size 10
        int randomValue = ThreadLocalRandom.current().nextInt(0, 10);
        if(randomValue == temp) {
           i--; // it will repeat the generation of random value if temp and randomValue is same
        } else {
           temp = randomValue; // you will put here the ne random value to be compared to next value
           System.out.println(randomValue);
    }

Upvotes: 1

Zabuzard
Zabuzard

Reputation: 25903

Just remember the last generated value and if equals then reject. Here is an example:

int lastRandomValue = -1;
boolean stop = false;
int attempts = 0;
final int maxAttempts = 100_000;

while (!stop) {
    int currentRandomValue = ThreadLocalRandom.current().nextInt(0, filteredArrayList.size());

    if (currentRandomValue != lastRandomValue) {
        // Use the value
        ...
        // Reset the counter
        attempts = 0;
        ...
        // Stop the generation process if generated enough values
        if (...) {
            stop = true;
        }
    } else {
        // Increment a counter
        attempts++;
    }

    if (attempts >= maxAttempts) {
        stop = true;
    }
}

Upvotes: 0

UnkJester
UnkJester

Reputation: 19

As Scary Wombat said, you'll want to compare the previous value to the newly randomized value in a loop (which I assume you are using, since we only see the one line.

Something like this...

int prevRandomNumber, currRandomNumber;
while (notFinished) {
    currRandomNumber = getRandom(); // your random number generator
    if (prevRandomNumber == currRandomNumber) { // if there would be two in a row
        continue;                               //   try again
    } else {                                    // otherwise, add to array
        addNumberToArray(currRandomNumber);     
        prevRandomNumber = currRandomNumber;
    }
}

Upvotes: 0

Related Questions