gpt4 book ai didi

java - 取消混洗复合混洗列表

转载 作者:搜寻专家 更新时间:2023-11-01 02:24:43 24 4
gpt4 key购买 nike

我正在尝试取消混洗复合混洗列表。我无法弄清楚如何完成此任务。

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com