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 ?
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.
You can shuffle a list in place with random. shuffle() .
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.
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.
To easily prevent moving any number of elements simply
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With