Skip to content Skip to sidebar Skip to footer

Generate A Set Of Unique Numbers Java

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 havi

Solution 1:

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

Solution 2:

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.

Post a Comment for "Generate A Set Of Unique Numbers Java"