-3

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));
Community
  • 1
  • 1
user1078385
  • 344
  • 2
  • 6
  • 21

2 Answers2

6

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).

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Viktor Latypov
  • 14,289
  • 3
  • 40
  • 55
0

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.

OmniOwl
  • 5,477
  • 17
  • 67
  • 116
  • 1
    Can be very inefficient if you want to select 99 out of a sequence of 100. – Andrew Thompson May 20 '12 at 23:39
  • Well yeah, but I never talked about efficiency in this, so. – OmniOwl May 20 '12 at 23:39
  • Why did my answer get 2 downvotes? This is a pretty legit way of doing it. If the user wanted an efficient version, I would have worked towards that as well. Jesus christ. – OmniOwl May 20 '12 at 23:42
  • 2
    I can only account for one of them. Shrugging your shoulders when warned of an inefficient approach - rather than doing something about it (e.g. an edit) is the main reason. – Andrew Thompson May 20 '12 at 23:44
  • Even if I edited this, it would still receive a downvote. This site some times :/ – OmniOwl May 20 '12 at 23:45
  • 2
    +1 to undo some of this harshness. This approach is plenty fast for this scenario and probably most others. It's worth noting that there's a better solution, but this is the simple and easy solution that first comes to mind. Downvotes are for answers that are wrong. At worst this answer deserves a 0, and because it has educational value probably a bit more. – filip-fku May 20 '12 at 23:48