, , , , :
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]