day03.pl (1344B) - raw
1 #!/usr/bin/env perl 2 3 use strict; 4 use warnings; 5 use v5.22; 6 #use Data::Dumper; 7 8 if (@ARGV !=1) { 9 die "Usage: $0 [input-filename]"; 10 } 11 12 my $input_filename = $ARGV[0]; 13 open my $filehandle, '<', $input_filename or 14 die "Could not open input file $input_filename: $!"; 15 16 chomp( my @input = ( <$filehandle> ) ); 17 18 # Part 1 19 my $len = length($input[0]) - 1; # number of bits - 1 20 my %count_0 = (); 21 my %count_1 = (); 22 my $gamma_rate = ""; 23 my $epsilon_rate = ""; 24 25 foreach (@input) { 26 my @diagnostic = split //; 27 for (0 .. $len) { 28 if ($diagnostic[$_]) { # bit at position $_ is 1 29 $count_1{$_}++; 30 } else { 31 $count_0{$_}++; 32 } 33 } 34 } 35 36 for (0 .. $len) { # find which bit occurs the most at each position 37 if ($count_0{$_} > $count_1{$_}) { 38 $gamma_rate .= "0"; 39 $epsilon_rate .= "1"; 40 } else { 41 $gamma_rate .= "1"; 42 $epsilon_rate .= "0"; 43 } 44 } 45 46 # From the perlfunc man page: 47 # oct EXPR 48 # oct Interprets EXPR as an octal string and returns the corresponding 49 # value. (If EXPR happens to start off with "0x", interprets it as a 50 # hex string. If EXPR starts off with "0b", it is interpreted as a 51 # binary string. Leading whitespace is ignored in all three cases.) 52 say oct("0b" . $gamma_rate) * oct("0b" . $epsilon_rate);