Generate a set of unique numbers java [duplicate]

2019-09-26 04:02发布

问题:

Possible Duplicate:
Generate unique random numbers in Java

I am creating a lottery app for android which will generate a set of 6 numbers between 1 and 49. The problem I am having is how can I make these numbers unique.

Random r = new Random();
int n1=r.nextInt(48) + 1;
ball1.setText(String.valueOf(n1));
int n2=r.nextInt(48) + 1;
ball2.setText(String.valueOf(n2));
int n3=r.nextInt(48) + 1;
ball3.setText(String.valueOf(n3));
int n4=r.nextInt(48) + 1;
ball4.setText(String.valueOf(n4));
int n5=r.nextInt(48) + 1;
ball5.setText(String.valueOf(n5));
int n6=r.nextInt(48) + 1;
ball6.setText(String.valueOf(n6));

回答1:

It's a very simple solution. You make a for loop which makes new numbers, and if it's the first number you make, you add it to a temporary array. Then every time you generate a new number, you check with your array of already existing numbers, and then if it's not unique, you add 1 to the counter of your for loop.

This will keep going until you have all your unique numbers. Hope that made sense.



回答2:

This is a classic task. Take the array of [1..49] values, generate 6 random permutations and then take 6 first items of the permuted array.

This is called shuffling (Fisher–Yates shuffle).