2015-08-29 2 views
2

The birthday paradox says that the probability that two people in a room will have the same birthday is more than half as long as the number of people in the room (n), is more than 23. This property is not really a paradox, but many people find it surprising. Design a C++ program that can test this paradox by a series of experiments on randomly generated birthdays, which test this paradox for n =5, 10, 15, 20, . . . , 100. You should run at least 10 experiments for each value of n and it should output, for each n, the number of experiments for that n, such that two people in that test have the same birthday.Pourquoi ai-je cette erreur dans mon code JAVA?

package birth; 
import java.util.Random; 

/* Question: 
The birthday paradox says that the probability that two people in a room 
will have the same birthday is more than half as long as the number of 
people in the room (n), is more than 23. This property is not really a paradox, 
but many people find it surprising. Design a C++ program that can 
test this paradox by a series of experiments on randomly generated birthdays, 
which test this paradox for n =5, 10, 15, 20, . . . , 100. You should run 
at least 10 experiments for each value of n and it should output, for each 
n, the number of experiments for that n, such that two people in that test 
have the same birthday. 
*/ 

public class birth { 

public static final int YEAR = 365; 

public static void main(String[] args) 
{ 

    int numOfPeople = 5; 
    int people = 5; 

    //DOB array 
    int[] birthday = new int[YEAR]; 



    //Creates an array that represents 365 days 
    for (int i = 0; i < birthday.length; i++) 
     birthday[i] = i + 1; 

    //Random Number generator 
    Random randNum = new Random(); 

    int iteration = 1; 

    //iterates around peopleBirthday array 
    while (numOfPeople <= 100) 
    { 
     System.out.println("Iteration: " + iteration); 
     System.out.println(); 
     //Creates array to holds peoples birthday 
     int[] peopleBirthday = new int[numOfPeople]; 


     //Assigns people DOB to people in the room 
     for (int i = 0; i < peopleBirthday.length; i++) 
     { 
      int day = randNum.nextInt(YEAR + 1); 
      peopleBirthday[i] = birthday[day]; 


     } 
     for (int i = 0; i < peopleBirthday.length; i++) 
     { 


      //stores value for element before and after 
      int person1 = peopleBirthday[i]; 
      int person2 = i + 1; 

      //Checks if people have same birthday 
      for (int j = person2; j < peopleBirthday.length; j++) 
      { 


       //Prints matching Birthday days 
       if (person1 == peopleBirthday[j]) 
       { 
        System.out.println("P1: " + person1 + " P2: " + peopleBirthday[j]); 
        System.out.println("Match!!! \n"); 

       } 
      } 
     } 


     //Increments the number of people in the room 
     numOfPeople += 5; 
     iteration++; 
    } 

    } 
} 

Je reçois une erreur: java.lang.ArrayIndexOutOfBoundsException: 365 Je ne peux pas comprendre ce qui ne va pas avec mon code

+1

'Concevoir un programme C++ ...' mais votre code est dans 'Java'. Oups – sam

Répondre

2

Ce serait bien si vous avez fourni le numéro de ligne exact où l'exception a été levée (l'information est dans la trace de pile d'erreur que vous avez), mais il est très probable que le problème se produise ici:

int day = randNum.nextInt(YEAR + 1); // 365 + 1 = 366 
peopleBirthday[i] = birthday[day]; 

La documentation Random.nextInt dit:

Returns: the next pseudorandom, uniformly distributed int value between zero (inclusive) and bound (exclusive) from this random number generator's sequence.

Dans ce cas, vous appellent Random.nextInt avec une valeur de 366 (365 + 1), ce qui signifie que vous lisez efficacement un nombre aléatoire entre 0 et 365. Si jamais vous obtenez 365, cela fera birthday[day] jeter l'exception hors limites, comme l'index maximum de votre tableau est 364, pas 365.

Vous avez probablement voulu dire lire la valeur aléatoire au lieu de cette façon:

int day = randNum.nextInt(YEAR); // 365 (exclusive) 
1

Les tableaux en Java sont basés sur zéro. Si vous créez birthday avec une longueur de 365, les index seraient de 0 à 364.

Vous devez modifier cette ligne de ceci:

int[] birthday = new int[YEAR]; 

à ceci:

int[] birthday = new int[YEAR+1]; 
+0

Merci! Cela a résolu mon problème complètement! J'apprécie l'aide! – Chrismar

+0

Cela ne résout pas tout à fait le problème, bien qu'il fasse fonctionner votre programme. Comme @sstan l'a noté, vous générez des valeurs aléatoires de 0 à 365, c'est-à-dire 366 valeurs aléatoires différentes. Ainsi, vos expériences ne correspondront pas au problème original. ils seraient valables pour une année avec 366 jours, plutôt qu'une année avec 365 jours. (Ce qui est correct si vous voulez compter le 29 février, mais la façon dont le problème est généralement indiqué ne compte pas pour cela.) De plus, si vous voulez inclure le 29 février, vous devez le peser puisque les anniversaires du 2/29 ne se produisent 97/400 fois plus souvent que les autres jours.) – ajb

+0

Oh je vois! Ça a du sens. Merci pour l'aide. Je vous en suis reconnaissant. – Chrismar