#!/usr/bin/env perl use strict; use warnings; use v5.22; #use Data::Dumper; if (@ARGV !=1) { die "Usage: $0 [input-filename]"; } my $input_filename = $ARGV[0]; open my $filehandle, '<', $input_filename or die "Could not open input file $input_filename: $!"; chomp( my @input = ( <$filehandle> ) ); # Part 1 my $len = length($input[0]) - 1; # number of bits - 1 my %count_0 = (); my %count_1 = (); my $gamma_rate = ""; my $epsilon_rate = ""; foreach (@input) { my @diagnostic = split //; for (0 .. $len) { if ($diagnostic[$_]) { # bit at position $_ is 1 $count_1{$_}++; } else { $count_0{$_}++; } } } for (0 .. $len) { # find which bit occurs the most at each position if ($count_0{$_} > $count_1{$_}) { $gamma_rate .= "0"; $epsilon_rate .= "1"; } else { $gamma_rate .= "1"; $epsilon_rate .= "0"; } } # From the perlfunc man page: # oct EXPR # oct Interprets EXPR as an octal string and returns the corresponding # value. (If EXPR happens to start off with "0x", interprets it as a # hex string. If EXPR starts off with "0b", it is interpreted as a # binary string. Leading whitespace is ignored in all three cases.) say oct("0b" . $gamma_rate) * oct("0b" . $epsilon_rate);