2016-09-16 31 views
2

嘿傢伙我試圖讓有相同的生日的人數,但這種解決方案不工作。這個程序顯示0.0%。請幫助我...!。通過結構數據查找類似的生日

public double calculate(int size, int count) { 
    int matches = 0;//initializing an integer variable 
    boolean out = false; 
    List<Integer> days=new ArrayList<Integer>();// creating arraylist name days of type int 
    for (int j = 0; j <count; j++) { 
     for (int i = 0; i < size; i++) {// initializing for loop till less than size 
      Random rand = new Random(); // creating an object of random function 

      int Brday = rand.nextInt(364) + 0;//initializing the limit of randomc number chozen 

      days.add(Brday); //adding values to arraylist 
     } 

     for (int l = 0; l < size; l++) { 
      int temp = l;//assigning value of l to a variable 
      for (int k = l + 1; k < size; k++) { 
       if (days.get(k) == temp) {// check statement to check values are same 

        matches++;//incrementing variable 
        out = true; 
        mOut.print("Count does have same birthday" + matches); 
        break; 

       } else { 
        mOut.print("does not have same birthday"); 

       } 
      } 
      if (out) { 
       out = false; 
       break; 
      } 

     } 
    } 
    double prob = (double) matches/count; 
    mOut.print("The probability for two students to share a birthday is " + prob*100 + "."); 
    return prob;//returning double value of the function 
} 
+0

@RC。 OP沒有在對象中使用==,他將==與'Integer'和'int'結合使用,這會導致自動拆箱。 –

+0

@ErwinBolwidt你是對的,我的壞。 – 2016-09-16 08:25:28

+0

你不能使用[公式](https://en.wikipedia.org/wiki/Birthday_problem)嗎? – 2016-09-16 08:26:17

回答

0

其實,你得到的代碼是0%或100%。如果您想查看,請嘗試使用calculate(100, 100)進行調用。

在這段代碼中有兩件事是錯誤的。首先,如果您不止一次運行模擬(count> 1),那麼您在第二次迭代之前不會清除生日列表。

你的方法應該首先:

public double calculate(int size, int count) { 
    int matches = 0; 
    boolean out = false; 
    List<Integer> days; 
    for (int j = 0; j <count; j++) { 
     days = new ArrayList<Integer>(); 

其次,你不能比較兩個生日,但你生日比較列表索引。

這條線:

int temp = l;//assigning value of l to a variable 

應改爲:

int temp = days.get(l); // Remember the birthday at index l 

這些變化,你會得到一個更好的結果。

+0

非常感謝你這麼好的迴應。它現在正在工作,但是有一個問題,它需要花費很多時間才能獲得大的價值。這將是非常好的,如果你建議我也是這樣的解決方案...... –

+0

@FarasatNiazi我認爲你找到有用的答案。你能提出答案嗎?如果您將鼠標懸停在upvote按鈕上,您會在工具提示中看到這意味着「這個答案很有用」 –

+0

請給我建議一些耗時的解決方案和解決方案,可以處理大數值? –

相關問題