2017-06-07 54 views
1

在運行下面的代碼片段循環執行正確,但內容不會被添加的某些原因。ArrayList中不能添加元素由於函數調用

for(i=5;i<=500;i++) { 
    x.add(i); 
    check(x,i); 
} 

public static void check(ArrayList<Integer> x,Integer i){ 
    for(int j=0;j<x.size();j++){         
     for(int k=0;k<x.size();k++){ 
      if(x.get(j)!=i&& x.get(k)!=i){ 
       if(x.contains(x.get(k)+x.get(j))) 
        x.remove(Integer.valueOf(i)); 
      } 
     } 
    } 
} 
+0

是這應該刪除重複的值? – Sedrick

+0

no no ......它應該刪除存在一對的元素,其總和等於該元素。 – prtk419

+0

能否請您包括代碼的其餘部分,因爲它是很難判斷,你可以指導我怎麼做 – WIR3D

回答

1

您正在從列表中刪除int i而不是計算值。你做你的包含方法,你應該刪除該部分。每次運行它都會刪除你插入的任何參數。所以每次你添加一些東西,然後只是方法,並刪除你剛添加的東西。

+0

明白了....是一個愚蠢的錯誤.... – prtk419

+0

沒有問題,用一個複選標記打我,讓人們知道它完成並回答:)否則,人們將繼續發佈。 – RostSunshine

0

的任務是相當有趣的,但你試圖做的方式實在是太昂貴(和非常錯誤的,因爲你修改的迭代過程中的列表)

所以這裏有一點改進:

public static void main(String[] args) { 
    List<Integer> list = new ArrayList<>(); 
    IntStream.range(5, 500) 
     .filter(i -> !check(list,i)) // check first 
     .forEach(i -> list.add(i)); // add after 
    System.out.println(list); 
} 
// we assume (rightly so) that list is ordered 
private static boolean check(List<Integer> list, int value) { 
    boolean found = false; 
    for(int j=0; j < list.size(); j++){ 
     Integer leftSide = list.get(j); 
     if(leftSide > value/2){ 
      break;     // as the check is symmetrical, stop after value/2 has been overtaken 
     } 
     Integer complementaryValue = value - leftSide; 
     for(int k=j+1; k < list.size(); k++){ // iterate over the rest of the list (because right is necessarily > left) 
      Integer rightSide = list.get(k); 
      if(rightSide > complementaryValue){ 
       break;    // no need to continue further 
      } 
      if(complementaryValue.equals(rightSide)){ 
       found = true; 
       System.out.println(value+" = "+leftSide+" + "+rightSide); 
       break; 
      } 
     } 
     if(found){ 
      break; // or return true 
     } 
    } 
    return found; 
} 

你可以試試。

這仍然遠遠沒有達到最佳,工作仍然可以在內部循環中完成。對互補價值的二分搜索會更好。

的最終列表是

[5,6,7,8,9,10,20,21,22,23,24,35,36,37,38,39,50,51 ,52,53,54,65,66,67,68,69,80,81,82,83,84,95,96,97,98,99,110,111,112,113,114,125,126 ,127,128,129,140,​​141,142,143,144,155,156,157,158,159,170,171,172,173,174,185,186,187,188,189,200,201 ,202,203,204,215,216,217,218,219,230,231,232,233,234,245,246,247,248,249,260,261,262,263,264,275,276,以及其中之一或其組合,277,278,279,290,291,292,293,294,305,306,307,308,309,320,321,322,323,324,335,336,337,338,339,350,351 ,352,353,354,365,366,367,368,369,380,381,382,383,384,395,396,397,398,399,410,411,412,413,414,425,426 ,427,4 284,440,441,442,443,444,455,456,457,458,459,470,471,472,473,474,485,486,487,488,489]