I want to generate 6 different random numbers by using Math.random and store them into an array. How can I make sure that they are different? I know I need to use for-loop to check the array but how...
This is the range. I only need numbers between 1 and 49. ( 1 + (int) (Math.random() * 49) )
Just keep generating numbers and adding them to the array as long as they are unique; psuedocode:
Generate any 6 numbers (not necessarily different). Order them.
a1 <= a2 <= a3 <= a4 <= a5 <= a6
Now take these 6 numbers
a1 < a2 + 1 < a3 + 2 < a4 + 3 < a5 + 4 < a6 + 5
These 6 are different and random.
The idea of this construct comes from some combinatorial proofs.
Its advantage is that it's simple, fast, and deterministic.
I think the time complexity is
O(count*log(count))
.I wonder if it can be improved.
I've just came up with a small idea for Java 8-.
Instead of checking that the array has no duplicates, you can use a bit more smartness while generating the numbers, such that uniqueness is enforced at the outset.
boolean[]
as long as your range (49 entries);boolean[]
;boolean[]
, counting all the non-crossed entries. Stop when you reach the count equal to the random number generated in step 5. The number corresponding to that entry is your output number;That code generate numbers from 6 to 0 and save in ArrayList.
If generated number was duplicated the program generate numbers again.
If generated number is different that number is added.
Code:
In Java 8:
In Java 7:
Just a little messier. Not helped by the fact that it's pretty tedious to unbox the
Set<Integer>
into anint[]
.It should be noted that this solution should be fine of the number of required values is significantly smaller than the range. As
1..49
is quite a lot larger than6
you're fine. Otherwise performance rapidly degrades.