user3840825
user3840825

Reputation: 29

Randomize numbers from a specific array without duplicates

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

Answers (4)

Mateva
Mateva

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

Eypros
Eypros

Reputation: 5723

In general you can do in of the following:

  • Create random numbers and keep them in a Set so that they are unique and keep pooling them until the desired amount of random numbers is achieved.
  • If you have a pool by which you want to pool numbers you can create an array (as you do) and then shuffle this array. Why this solution does not work for you? I think you are mixing the 2 solution and get duplicates.

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

TheLostMind
TheLostMind

Reputation: 36304

Create a Collection (Set - because of the no-duplicates requirement) using your array. Use Collections.shuffle(mySet);

Upvotes: 0

akash yadav
akash yadav

Reputation: 349

int pos =shuffled array[random.nextInt(4)]
int random_num_from_shuffled_array =  shuffled array[pos];

Upvotes: 0

Related Questions