commit 5c3c265c68104064495e8431c0c89bb1dd00ead4
parent 1ffe91aef32774bb17524cec9e3ad2648a7c26e2
Author: Samir Parikh <noreply@samirparikh.com>
Date: Fri, 3 Dec 2021 15:35:35 +0000
update day03.pl to get working solution for Part 1
Diffstat:
M | day03.pl | | | 26 | ++++++++++---------------- |
1 file changed, 10 insertions(+), 16 deletions(-)
diff --git a/day03.pl b/day03.pl
@@ -3,8 +3,7 @@
use strict;
use warnings;
use v5.22;
-use Data::Dumper;
-#use diagnostics;
+#use Data::Dumper;
if (@ARGV !=1) {
die "Usage: $0 [input-filename]";
@@ -17,12 +16,7 @@ open my $filehandle, '<', $input_filename or
chomp( my @input = ( <$filehandle> ) );
# Part 1
-#say scalar( grep { $input[$_] > $input[$_ - 1] } (1 .. $#input) );
-
-# Part 2
-#say scalar( grep { $input[$_ + 2] > $input[$_ - 1] } (1 .. $#input - 2) );
-
-my $len = length($input[0]) - 1;
+my $len = length($input[0]) - 1; # number of bits - 1
my %count_0 = ();
my %count_1 = ();
my $gamma_rate = "";
@@ -30,9 +24,8 @@ my $epsilon_rate = "";
foreach (@input) {
my @diagnostic = split //;
- #say join(":", @diagnostic);
for (0 .. $len) {
- if ($diagnostic[$_]) {
+ if ($diagnostic[$_]) { # bit at position $_ is 1
$count_1{$_}++;
} else {
$count_0{$_}++;
@@ -40,10 +33,7 @@ foreach (@input) {
}
}
-#print Dumper ( \%count_0 );
-#print Dumper ( \%count_1 );
-
-for (0 .. $len) {
+for (0 .. $len) { # find which bit occurs the most at each position
if ($count_0{$_} > $count_1{$_}) {
$gamma_rate .= "0";
$epsilon_rate .= "1";
@@ -53,6 +43,10 @@ for (0 .. $len) {
}
}
-#say $gamma_rate;
-#say $epsilon_rate;
+# 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);