是否有Collections.shuffle(List<?> list)
的反函数能够从Collections.shuffle(List<?> list)
的结果中提供数组的值?
答案 0 :(得分:3)
不。你能做的最好的事情是创建两个数组,一个从另一个克隆,然后只有一个数组。
答案 1 :(得分:3)
您可以使用Collection.shuffle(Collection,Random)并使用已知种子创建随机,然后使用具有相同种子的新Random的有序整数重新洗牌,以便获得映射: / p>
long seed = System.currentTimeMillis();//A random seed
List<String> in = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h");
System.out.println("original: \t" + in);
Collections.shuffle(in, new Random(seed));
System.out.println("shuffled: \t" + in);
//Ordered list of integers from 0 to in.size()
List<Integer> mapping = IntStream.range(0, in.size()).boxed().collect(Collectors.toList());
Collections.shuffle(mapping, new Random(seed));//same seed -> same shuffle
String[] out = new String[in.size()];
for(int i = 0; i < out.length; i++)
out[mapping.get(i)] = in.get(i);
System.out.println("out: \t\t" + Arrays.toString(out));
输出:
original: [a, b, c, d, e, f, g, h]
shuffled: [f, h, c, e, d, g, a, b]
out: [a, b, c, d, e, f, g, h]