Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use strict;
- my $DAYS_IN_YEAR = 365;
- my $NUM_SIMULATIONS = 10000;
- my $DISPLAY_PROGRESS = 100;
- my %h_friend_count_to_simulation_count = ();
- my %h_unclaimed_birthdays = ();
- my ($SEPARATOR, $NEWLINE) = ("\t", "\n");
- run_all_the_simulations();
- print_the_results();
- sub run_all_the_simulations {
- for(my $i = 0; $i < $NUM_SIMULATIONS; $i++) {
- run_a_simulation();
- print $i.$NEWLINE if($i % $DISPLAY_PROGRESS == 0);
- }
- }
- sub print_the_results {
- open(OUT, ">", "BirthdayResults.txt");
- print OUT join($SEPARATOR, "Friend Count", "Simulation Count").$NEWLINE;
- foreach(sort keys %h_friend_count_to_simulation_count) {
- print OUT join($SEPARATOR, $_ , $h_friend_count_to_simulation_count{$_} ).$NEWLINE;
- }
- close OUT;
- }
- sub run_a_simulation {
- cleanup_and_setup();
- my $friend_count = 0;
- while( keys( %h_unclaimed_birthdays ) > 0) {
- add_a_friend();
- $friend_count++;
- }
- $h_friend_count_to_simulation_count{$friend_count}++;
- }
- sub cleanup_and_setup {
- for(my $i = 1; $i <= $DAYS_IN_YEAR; $i++) {
- $h_unclaimed_birthdays{$i} = 1;
- }
- }
- sub add_a_friend {
- my $friends_birthday = 1 + int(rand() * $DAYS_IN_YEAR);
- delete $h_unclaimed_birthdays{$friends_birthday};
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement