0

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?

1
  • int pos =shuffled array[random.nextInt(4)] Commented Jul 18, 2014 at 6:59

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.