2017-06-17 74 views
1

我想找到一种方法来更新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); 

回答

0

而是从列表中删除随机元素, 东西它会更简单,更有效的改组列表, 始终以最后一个元素。

List<Integer> selection = IntStream.range(1, 13).boxed().collect(Collectors.toList()); 
Collections.shuffle(selection); 

该列表的最后一个元素将是随机的。 删除最后一个元素很便宜。 (如果在您的示例中为ArrayList,则删除中间的元素需要复制之后的元素。)

+0

感谢雅诺斯你非常聪明的选择。如果我理解正确:1)我的新方法等于混洗列表的最后一个元素。 2)之后最后一个元素被删除。 –

+0

@ArjenPeters是正确的,然后删除最后一个元素,或使用索引来跟踪下一个要选择的元素。 – janos

+0

@Jonas Roger!我想我应该玩一下。用method = selection.get(selection.size() - 1); selection.remove(selection.size() - 1);该列表保持相同的长度。 –

0

你可以在并发修改的情况下使用Iterator。像

List<Integer> selection = new ArrayList<>(); 

for (Iterator<Integer> iterator = selection.iterator(); iterator.hasNext();) { 
    Integer val = iterator.next(); 
    if (check_for_condition) { 
     // Remove the current element from the iterator and the list. 
     iterator.remove(); 
    } 
} 
+0

谢谢!我之前有一个非常相似的迭代器,它的工作原理是在条件为真时除去元素,但它不会像我期望的结果中所述的那样在几次迭代中更新选择的总体内容。但我会仔细检查它并回到你身边。 –

+0

做接受的答案,如果它的工作 – Ravi