【发布时间】:2017-11-20 05:42:23
【问题描述】:
我正在尝试找到一种方法来更新 ArrayList 的内容,如果根据条件迭代地删除一个元素。我所拥有的是一种算法,它使用用户选择的方法(通过 switch case)以特定方式解决问题。但是,如果经过一定次数的迭代后没有发现改进,它会随机选择不同的可用方法(案例)。
目标: 如果选择了一种方法,则它不应再次可用。
代码:
public Solution solve() throws IOException, EclipseException {
// Account for all the available switch cases
ArrayList<Integer> selection = new ArrayList<Integer>();
for(int y = 1; y < 12; y++) {
selection.add(new Integer(1*y));
}
ArrayList<Integer> listToKeep = new ArrayList<Integer>();
for (int i = 0; i < iterations; i++) {
// Iterative process with a counter for each iteration that provides
// no improvement
if (counter == 6) {
for (Integer num : selection) {
if (num != method){
listToKeep.add(num);
}
}
selection.clear();
selection.addAll(listToKeep);
System.out.println("Sent for selection " + selection);
Random rand = new Random();
method = selection.get(rand.nextInt(selection.size()));
System.out.println("New randomly selected method is: " + method);
solve(method);
}
}
return bestSolution;
}
期望的结果:
All cases: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Initital method chosen: 1
Sent for selection [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
New randomly selected method is: 8
Sent for selection [2, 3, 4, 5, 6, 7, 9, 10, 11]
New randomly selected method is: 9
etc.
问题: for 循环一直引用包含所有数字的原始 ArrayList 选择(而不是基于 listToKeep 更新的),并且只删除最后选择的案例。
问题: 如何确保每次迭代都正确更新选择 ArrayList?
非常感谢任何反馈或替代方法!
解决方案编辑 18-06
if (!alreadyExecuted){
selection = IntStream.range(1, 12).boxed().collect(Collectors.toList());
Collections.shuffle(selection);
}
alreadyExecuted = true;
int newMethod = selection.get(selection.size() - 1);
selection.remove(selection.size() - 1);
【问题讨论】: