How to avoid generating the same 2 random numbers twice in a row

Lucas Tony :

I am trying to set the background color of a view using a timer to change the color every few seconds, but often a color is set twice in a row due to the fact that the random number referring to a specific color is generated twice. How can I change the code to avoid generating the same random number twice in a row?

final Runnable runnable = new Runnable() {

    @Override
    public void run() {

        Random rand = new Random();
        int n = rand.nextInt(3);
        n += 1;


        switch (n){

            case 1:

                colorView.setBackgroundColor(Color.GREEN);
                break;

            case 2:

                colorView.setBackgroundColor(Color.MAGENTA);
                break;

            case 3:

                colorView.setBackgroundColor(Color.CYAN);
                break;

        }

    }
};
Jassem Ben Hamida :

The only way is to make a test if the old number equals to the newest generated.

    Random rand = new Random();
    int n = rand.nextInt(3);
    n += 1;
    while (n == oldValue) {
        n = rand.nextInt(3);
        n += 1;
    }
    switch (n){
    ...
    }
    oldValue = n; //The oldValue should be global

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=328041&siteId=1