commit 25c5ebeb639ec2eaa52b3804099dfd6d5a0eec99
parent 016d954754a4b9d734650ddd755b98f5e6d105c7
Author: Samir Parikh <noreply@samirparikh.com>
Date: Fri, 3 Dec 2021 21:20:29 +0000
update day03-2.pl to start filtering out those candidates that don't have the most frequently occuring bit at the current index
Diffstat:
A | day03-2.pl | | | 71 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
1 file changed, 71 insertions(+), 0 deletions(-)
diff --git a/day03-2.pl b/day03-2.pl
@@ -0,0 +1,71 @@
+#!/usr/bin/env perl
+
+use strict;
+use warnings;
+use v5.22;
+
+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> ) );
+
+my $len = length($input[0]) - 1; # number of bits - 1
+my @numbers;
+foreach (@input) {
+# take each line, split it into an array, and push a reference to
+# that annonymous array into @numbers
+ push (@numbers, [split //]);
+}
+
+# create array copy to store oxygen generator rating candidates
+my @ogr = @numbers;
+
+while ( scalar ( @ogr ) > 1 ) { # while we still have more than one ogr
+ say "\@ogr array has ", scalar(@ogr), " elements";
+ foreach my $index (0 .. $len) { # iterate through each bit
+ # bit counters
+ say "evaluating index $index";
+ my %count_0 = ();
+ my %count_1 = ();
+ foreach my $num (@ogr) { # iterate through each ogr candidate
+ #say $num->[$index];
+ if ($num->[$index]) { # bit at position index is 1
+ $count_1{$index}++;
+ } else {
+ $count_0{$index}++;
+ }
+ }
+ my $most_freq_bit =
+ ($count_1{$index} >= $count_0{$index}) ? 1 : 0;
+ #say "mfbai = $most_freq_bit";
+ my $mfb_count;
+ if ($most_freq_bit) {
+ $mfb_count = $count_1{$index};
+ } else {
+ $mfb_count = $count_0{$index};
+ }
+ say "there are more $most_freq_bit bits ($mfb_count)";
+ my @temp_ogr; # temp array to hold elements whose bits match the
+ # most frequently occuring one
+ foreach my $num (@ogr) {
+ if ($num->[$index] == $most_freq_bit) {
+ say "keeping @$num";
+ push( @temp_ogr, $num);
+ }
+ }
+ #foreach my $num (@ogr) {
+# remove any candidates from ogr UNLESS the bit at the current index is
+# the most frequent
+ #splice(@ogr, $index, 1) unless ($num->[$index] == $most_freq_bit);
+ #}
+ say "--- go to next index ---";
+ }
+ @ogr = ();
+}
+
+#say @{$ogr[0]};