Advertisement
Guest User

Birthday Monte Carlo

a guest
Apr 28th, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.19 KB | None | 0 0
  1. use strict;
  2.  
  3. my $DAYS_IN_YEAR = 365;
  4. my $NUM_SIMULATIONS = 10000;
  5. my $DISPLAY_PROGRESS = 100;
  6.  
  7. my %h_friend_count_to_simulation_count = ();
  8. my %h_unclaimed_birthdays = ();
  9. my ($SEPARATOR, $NEWLINE) = ("\t", "\n");
  10.  
  11. run_all_the_simulations();
  12. print_the_results();
  13.  
  14. sub run_all_the_simulations {
  15.     for(my $i = 0; $i < $NUM_SIMULATIONS; $i++) {
  16.         run_a_simulation();
  17.         print $i.$NEWLINE if($i % $DISPLAY_PROGRESS == 0);
  18.     }
  19. }
  20.  
  21. sub print_the_results {
  22.     open(OUT, ">", "BirthdayResults.txt");
  23.     print OUT join($SEPARATOR, "Friend Count", "Simulation Count").$NEWLINE;
  24.     foreach(sort keys %h_friend_count_to_simulation_count) {
  25.         print OUT join($SEPARATOR, $_ , $h_friend_count_to_simulation_count{$_} ).$NEWLINE;
  26.     }
  27.     close OUT;
  28. }
  29.  
  30. sub run_a_simulation {
  31.     cleanup_and_setup();
  32.     my $friend_count = 0;
  33.     while( keys( %h_unclaimed_birthdays ) > 0) {
  34.         add_a_friend();
  35.         $friend_count++;
  36.     }
  37.     $h_friend_count_to_simulation_count{$friend_count}++;
  38. }
  39.  
  40. sub cleanup_and_setup {
  41.     for(my $i = 1; $i <= $DAYS_IN_YEAR; $i++) {
  42.         $h_unclaimed_birthdays{$i} = 1;
  43.     }
  44. }
  45.  
  46. sub add_a_friend {
  47.     my $friends_birthday = 1 + int(rand() * $DAYS_IN_YEAR);
  48.     delete $h_unclaimed_birthdays{$friends_birthday};
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement