我想找到一种方法来更新ArrayList的内容,其中一个元素,如果基于条件迭代删除。我拥有的是一种使用用户选择的方法(通过开关盒)以特定方式解决问题的算法。但是,如果在一定量的迭代之后没有发现改进,它会随机选择一种不同的可用方法(大小写)。更新内容Arraylist每迭代
目标: 如果选择了一种方法,它不应该再次可用。
代码:
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的选择on基于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);
感谢雅诺斯你非常聪明的选择。如果我理解正确:1)我的新方法等于混洗列表的最后一个元素。 2)之后最后一个元素被删除。 –
@ArjenPeters是正确的,然后删除最后一个元素,或使用索引来跟踪下一个要选择的元素。 – janos
@Jonas Roger!我想我应该玩一下。用method = selection.get(selection.size() - 1); selection.remove(selection.size() - 1);该列表保持相同的长度。 –