Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent the overlapping random numbers

Tags:

java

random

How would i prevent duplicating numbers from random numbers. I need to generate 5 numbers between 1 and 9 that are each different. I would often get same numbers like 23334, how can i prevent that? Any help would be great!

    int num2 = (int) Math.round((Math.random()*9) +1);
    int num1 = (int) Math.round((Math.random()*9) +1);
    int num5 = (int) Math.round((Math.random()*9) +1);
    int num3 = (int) Math.round((Math.random()*9) +1);
    int num4 = (int) Math.round((Math.random()*9) +1);
like image 679
Marcus Liu Avatar asked Jan 20 '15 05:01

Marcus Liu


People also ask

Can you generate the same random numbers everytime?

random seed() example to generate the same random number every time. If you want to generate the same number every time, you need to pass the same seed value before calling any other random module function.

What happens if you use the random number multiple times in your program?

If you use randomNumber() multiple times in your program it will generate new random numbers every time. You can think of each randomNumber() like a new roll of a die.

Why is 17 the most common random number?

Seventeen is: Described at MIT as 'the least random number', according to the Jargon File. This is supposedly because in a study where respondents were asked to choose a random number from 1 to 20, 17 was the most common choice. This study has been repeated a number of times.


2 Answers

One option is to use shuffle algorithm (e.g. Fisher-Yates shuffle ) to generate random sequence from 1 to 9, then take first 5 numbers of the sequence

Further explanation on StackOverflow: https://stackoverflow.com/a/196065/950427

like image 75
Phuong Nguyen Avatar answered Oct 03 '22 12:10

Phuong Nguyen


Set<Integer> set=new HashSet<>();
while (set.size()<5) {
    set.add( Math.round((Math.random()*9) +1));
}

After the set is filled you have 5 unique random numbers.

UPDATE: just to illustrate Jared Burrows' comment

like image 35
StanislavL Avatar answered Oct 03 '22 11:10

StanislavL