作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在尝试取消混洗复合混洗列表。我无法弄清楚如何完成此任务。
public static void main(String[] args) {
// Setup random
Random rand = new Random();
rand.setSeed(5);
// Setup list
ArrayList<Character> list = new ArrayList<Character>(Arrays.asList('v','y','2','w','9','n','8','v','a'));
// Compound shuffle list
for(int i=0;i<5;i++)
Collections.shuffle(list, rand);
// un-shuffle list
// TODO
}
还有我的 un-shuffle 方法。
private static void unshuffle(ArrayList<?> list, Random rand) {
// Create the sequence backwards
int[] seq = new int[list.size()];
for(int i=seq.length; i>1; i--)
seq[i-1] = rand.nextInt(i);
// Traverse the sequence and swapping it inversely
for (int i=0; i<seq.length; i++)
Collections.swap(list, i, seq[i]);
}
编辑:修复了 ArrayList。
最佳答案
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<String>(Arrays.asList("A", "B", "C", "D", "E", "F", "G"));
compoundShuffle(list, 8, 13);
compoundUnshuffle(list, 8, 13);
System.out.println(list);
}
public static void compoundShuffle(List<?> list, int repetition, long seed) {
Random rand = new Random(seed);
for (int i = 0; i < repetition; i++)
Collections.shuffle(list, rand);
}
public static void compoundUnshuffle(List<?> list, int repetition, long seed) {
helper(list, repetition, seed);
}
private static <E> void helper(List<E> list, int repetition, long seed) {
List<Integer> indices = new ArrayList<Integer>();
int size = list.size();
for (int i = 0; i < size; i++)
indices.add(i);
compoundShuffle(indices, repetition, seed);
List<E> copy = new ArrayList<E>(list);
for (int i = 0; i < size; i++)
list.set(indices.get(i), copy.get(i));
}
}
关于java - 取消混洗复合混洗列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27770496/
我是一名优秀的程序员,十分优秀!