How to shuffle a list except an item?

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

I know I can use the method

Collections.shuffle(list);

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

How can i do this?

+4
source share
3 answers

You can shuffle the collection and then restore 7 to the second 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));

Like others, you can also delete the item whose location you want to keep before shuffling, and add it later in the same place.

ArrayLists ( ), indexOf , ( ) ArrayList, , / , .

+8

  • ,
  • ,
  • ( , ).
+5

, , , , :

public static <T> void shuffleExcept(final List<T> list, final int position) {
    List<T> view = new AbstractList<T>() {
        @Override
        public T get(int index) {
            return list.get(index >= position ? index+1 : index);
        }

        @Override
        public T set(int index, T element) {
            return list.set(index >= position ? index+1 : index, element);
        }

        @Override
        public int size() {
            return list.size()-1;
        }
    };
    Collections.shuffle(view);
}

Here we create a “view” of the original list, which is an entire list, except for the element we want to keep (we just shift the indices of the subsequent elements). Then we shuffle this opinion. What is the beauty of interfaces: you can ask an existing method to do something else by simply passing in a new implementation of the interface.

Usage example:

List<Integer> input = Arrays.asList(0, 7, 2, 1, 6, 5);
shuffleExcept(input, 1);
System.out.println(input);
shuffleExcept(input, 1);
System.out.println(input);
shuffleExcept(input, 1);
System.out.println(input);
shuffleExcept(input, 1);
System.out.println(input);
shuffleExcept(input, 1);
System.out.println(input);
shuffleExcept(input, 1);
System.out.println(input);
shuffleExcept(input, 1);
System.out.println(input);

Typical Output:

[6, 7, 5, 2, 1, 0]
[5, 7, 6, 1, 2, 0]
[6, 7, 2, 0, 5, 1]
[6, 7, 2, 0, 5, 1]
[2, 7, 0, 5, 6, 1]
[6, 7, 0, 2, 5, 1]
[5, 7, 2, 0, 1, 6]
+2
source

All Articles