Guest User

Untitled

a guest
Jan 21st, 2019
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. /**
  2. * Simulate choosing people at random and checking the day of the year they
  3. * were born on. If the birthday is the same as one that was seen previously,
  4. * stop, and output the number of people who were checked.
  5. */
  6. public class BirthdayProblem {
  7.  
  8. public static void main(String[] args) {
  9.  
  10. boolean[] used; // For recording the possible birthdays
  11. // that have been seen so far. A value
  12. // of true in used[i] means that a person
  13. // whose birthday is the i-th day of the
  14. // year has been found.
  15.  
  16. int count; // The number of people who have been checked.
  17.  
  18. used = new boolean[365]; // Initially, all entries are false.
  19.  
  20. count = 0;
  21.  
  22. while (true) {
  23. // Select a birthday at random, from 0 to 364.
  24. // If the birthday has already been used, quit.
  25. // Otherwise, record the birthday as used.
  26.  
  27. int birthday; // The selected birthday.
  28. birthday = (int)(Math.random()*365);
  29. count++;
  30.  
  31. System.out.printf("Person %d has birthday number %d%n", count, birthday);
  32.  
  33. if ( used[birthday] ) {
  34. // This day was found before; it's a duplicate. We are done.
  35. break;
  36. }
  37.  
  38. used[birthday] = true;
  39.  
  40. } // end while
  41.  
  42. System.out.println();
  43. System.out.println("A duplicate birthday was found after "
  44. + count + " tries.");
  45. }
  46.  
  47. } // end class BirthdayProblem
Add Comment
Please, Sign In to add comment