2016-09-16 4 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

[수식] (https://en.wikipedia.org/wiki/Birthday_problem)을 사용할 수 없습니까? –

답변

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 수 있습니까? upvote 버튼 위로 마우스를 가져 가면 "이 대답은 유용합니다"라는 툴팁에 표시됩니다. –

+0

큰 값으로 작업 할 수있는 솔루션과 솔루션을 제안 해주십시오. –