Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shuffle list except an element?

Tags:

java

shuffle

I have a list integer with value elements : 0, 7, 2, 1, 6, 5.

I know that I can use method

Collections.shuffle(list);

to shuffle my list. But I do not want change value of 2nd position. It should be always 7.

How can I do that ?

like image 400
CauCuKien Avatar asked Jun 28 '15 09:06

CauCuKien


People also ask

How do you randomize the order of items in a list?

Python Random shuffle() Method The shuffle() method takes a sequence, like a list, and reorganize the order of the items. Note: This method changes the original list, it does not return a new list.

How do you shuffle list values?

You can shuffle a list in place with random. shuffle() .

How do you shuffle elements in DART list?

shuffle method Null safety Shuffles the elements of this list randomly. final numbers = <int>[1, 2, 3, 4, 5]; numbers. shuffle(); print(numbers); // [1, 3, 4, 5, 2] OR some other random result.


2 Answers

You can shuffle the Collection and then restore the 7 to the 2nd position :

Collections.shuffle(list);
list.set(list.indexOf(7),list.get(2));
list.set(2,7);

Or shorter :

Collections.shuffle(list);
Collections.swap(list, 2, list.indexOf(7));

As others suggested, you can also remove the element whose location you wish to preserve prior to the shuffling, and add it later to the same location.

Both ways should take similar time for ArrayLists (linear at the worst case), since in my answer indexOf would take linear time, but removing and adding an element in the alternative solution (especially if the index is close to the start of the list) would take linear time for ArrayList, since all the elements following the removed/added index has to be pushed to a new index.

like image 129
Eran Avatar answered Sep 28 '22 01:09

Eran


To easily prevent moving any number of elements simply

  • Remove them from list,
  • shuffle rest of elements,
  • put them back at their original position (start from left to avoid problem with elements shifting to the right).
like image 43
Pshemo Avatar answered Sep 28 '22 01:09

Pshemo