Reputation: 16790
I am writing an Android app and I want to generate random numbers.
But, Java's RandomGenerator gives me only pseudo random numbers. The numbers repeat and not all the numbers are covered.
I want something that will give me non-repeating numbers and will cover all the numbers. How do I do that?
Upvotes: 2
Views: 634
Reputation: 533530
You can put all random values you want into a List and shuffle it.
List<Integer> numbers = ...
Collections.shuffle(numbers);
This will give you unique numbers in a random order.
Upvotes: 7
Reputation: 9154
You could fill a data structure with the numbers you want to loop over, then randomize the order of the elements in the structure and pull them out one by one. Alternatively, you could randomly pick indexes, and retrieve elements at those indexes. Whichever you do (you would choose the one more efficient for the specific data structure), you be sure to remove this element as you grab it. As you keep going your data structure will get smaller and smaller until you've received every element and have nothing left. This also ensures you'll never hit the same number twice, because you'll have removed it from your pool of possible numbers.
Upvotes: 0