Skip to content Skip to sidebar Skip to footer

Java Random Number With No Duplicate

I need to generate random numbers in 6 different edittext. Unfortunately the random numbers duplicates. I need unique numbers from the range I set. rndNumber = rndNumbers.

Solution 1:

Wrap the random number generator to store the results in a set. When you generate a number if it exists in the set, do it again:

Comments made by others about the for loops are also valid...

pseudo code:

classMyRandomNums {
    Set<Integer> usedNums;

    publicintgetRandom()
    {
        int num = random.nextInt();
        while(usedNums.contains(num)) {
            num = random.nextInt();
        }
        usedNums.add(num);
        return num;
    }

    publicintreset()
    {
        usedNums.clear();
    }
}

Solution 2:

All of your for-loops loop once. Why:

for (int nbr = 1; nbr < 2; nbr++) {
    rndNumber = rndNumbers.nextInt(max);
    num1.setText(Integer.toString(rndNumber));
}

when you can just do:

rndNumber = rndNumbers.nextInt(max);
num1.setText(Integer.toString(rndNumber));

?

Solution 3:

intmin = 0;
intmax = 100;
List<Integer> randoms = new ArrayList<Integer>();
for(int i = min; i <= max; i++) randoms.add(i);
Collections.shuffle(randoms);

Then you can use it like this:

int randomNumber = randoms.remove(0);

Solution 4:

for alpha numeric number try this

public String getRandomNum(int randomLength)
{   
    return new BigInteger(130, random).toString(32).toUpperCase().substring(0, randomLength);
}

if you want only numeric random number try this

publicString getRandomNum(int randomLength)
{
    int value = (int)(Math.random() * 9999);
    String format = "%1$0"+randomLength+"d";
    String randomNum = String.format(format, value);
    return randomNum;
}

Post a Comment for "Java Random Number With No Duplicate"