Reputation: 29
I have a array shuffled with some numbers I want to randomize the numbers in shuffled array without duplication am using below code
int shuffled array [] = {1,3,5,7,8}
Random random = new Random();
int random =shuffled array[random.nextInt(shuffled array.length)];
I am getting duplicate values.
How do I get to generate random number without any duplicate values?
Upvotes: 0
Views: 1365
Reputation: 812
You are actually using the Random
class and nextInt
which do not guarantee uniqueness of consecutive elements!
I guess what you need is achieved by Collections.shuffle
. See the documentation
Upvotes: 0
Reputation: 5723
In general you can do in of the following:
Set
so that they are unique and keep pooling them until the desired amount of random numbers is achieved. Edit:
About efficiency (if you are concerned about it): The first method uses a pseudorandom generator to produce the unique numbers. As the number of unique number in respect to the total possible numbers increases, (e.g. if you have an array and want all element to be picked up at random) then this approach might be inappropriate. If on the other hand you just want to pick 10 unique random numbers it is possibly efficient enough.
The shuffle
approach as states This method runs in linear time so it should be preferred in this case (yours that is).
Upvotes: 2
Reputation: 36304
Create a Collection
(Set
- because of the no-duplicates requirement) using your array.
Use Collections.shuffle(mySet);
Upvotes: 0
Reputation: 349
int pos =shuffled array[random.nextInt(4)]
int random_num_from_shuffled_array = shuffled array[pos];
Upvotes: 0