Behnam Ezazi
Behnam Ezazi

Reputation: 69

Random number generator without duplication

I am trying to have a piece of code in which a random number would be generated and will be saved in a collection so next time when another random number is generated i can check if this new number is already in list or not.

The main point of this method would be generating a number in ranged of 1 to 118, no duplicated number allowed.

Random rand = new Random();
    randomNum2 = rand.nextInt(118) + 1;
    if (!generated.contains(randomNum2))
    {
        String strTemp = "whiteElements\\"+String.valueOf(randomNum2)+".JPG";
        btnPuzzlePiece2.setIcon(new ImageIcon(strTemp));
        generated.add(randomNum2);
        btnPuzzlePiece2.repaint();
    }
    else 
        setPicForBtnGame1();

BUT the problem is in this piece of code as the program continues generating numbers the possibility to have a correct random number (in range without duplicating) imagine after running the method 110 times... the possibility for the method to generate a valid random number reduces to less than 1%... which leaves the program with the chance of never having the list of numbers from 1-118 and also too much waste of process.

so how can i write this correctly? p.s i thought of making 118 object and save them in a collection then generate a random object and after remove the object from the list so the next element has no chance of being duplicated.

Help me out please ...

Upvotes: 1

Views: 328

Answers (2)

Richard
Richard

Reputation: 1130

Wouldn't it be better to just generate something that can never be a duplicate? A random number with no duplicates is usually known as a UUID.

The easiest way to generate a UUID is to prefix your random number with the current system time in milliseconds. Of course there's a chance that it could be a duplicate but it's vanishingly small. Of course it might be long, so you'd want to then base64 encode it for example, to reduce it's size.

You can get a more or less guaranteed UUID down to about 8 characters using encoding.

Upvotes: -1

Kon
Kon

Reputation: 10810

Create a List, and populate it with the elements in your range. Then shuffle() the list, and the order is your random numbers. That is, the 0-th element is your first random number, the 1st element is your second random number, etc.

Upvotes: 5

Related Questions