2016-09-16 7 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あなたは正しく、私の悪いです。 –

+0

[formula](https://en.wikipedia.org/wiki/Birthday_problem)を使用できませんか? –

答えて

0

実際には、コードで0%または100%が得られます。表示したい場合はcalculate(100, 100)で呼び出してみてください。

このコードには2つの問題があります。まず、シミュレーションを2回以上実行した場合(count> 1)、2回目の反復の前に誕生日のリストをクリアすることはありません。第二に

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>(); 

、次の2つの誕生日を比較していないが、あなたがリストのインデックスへの誕生日を比較している:

あなたの方法で始まる必要があります。

このライン:

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できますか? upvoteボタンの上にマウスを移動すると、ツールチップに「この回答は役に立ちます」と表示されます。 –

+0

時間のかかるソリューションと大きな値で動作するソリューションを教えてください。 –