aoc2021

Advent of Code 2021 solutions in Perl.
git clone git://git.samirparikh.com/aoc2021
Log | Files | Refs | README

day03-2.pl (2231B) - raw


      1 #!/usr/bin/env perl
      2 
      3 use strict;
      4 use warnings;
      5 use v5.22;
      6 
      7 if (@ARGV !=1) {
      8     die "Usage: $0 [input-filename]";
      9 }
     10 
     11 my $input_filename = $ARGV[0];
     12 open my $filehandle, '<', $input_filename or
     13     die "Could not open input file $input_filename: $!";
     14 
     15 chomp( my @input = ( <$filehandle> ) );
     16 
     17 # Advent of Code 2021 Day 03 Part 2 
     18 my $len = length($input[0]) - 1; # number of bits - 1
     19 
     20 my @ogr = @input;
     21 foreach my $index (0 .. $len) { # first iterate through indices...
     22     my $count;
     23     foreach my $line (@ogr) { # ...and then through the numbers/lines
     24         if ( (split //, $line)[$index] ) { # if bit at position $index is 1
     25             $count++; # postive or zero count means 1
     26         } else {
     27             $count--; # negative count means 0
     28         }
     29     }
     30     # now see which is the most common bit at the index
     31     # if $count < 0, it's 0; otherwise it's 1
     32     my $most_freq_bit = ($count < 0) ? 0 : 1;
     33     my @temp_ogr = grep { (split //)[$index] == $most_freq_bit  } @ogr;
     34     @ogr = @temp_ogr; # replace real array with temporary array
     35     last if (scalar( @ogr ) == 1);
     36 }
     37 
     38 my @co2sr = @input;
     39 foreach my $index (0 .. $len) { # first iterate through indices...
     40     my $count;
     41     foreach my $line (@co2sr) { # ...and then through the numbers/lines
     42         if ( (split //, $line)[$index] ) { # if bit at position $index is 1
     43             $count++; # postive or zero count means 1
     44         } else {
     45             $count--; # negative count means 0
     46         }
     47     }
     48     # now see which is the most common bit at the index
     49     # if $count < 0, it's 0; otherwise it's 1
     50     my $most_freq_bit = ($count < 0) ? 0 : 1;
     51     my @temp_co2sr = grep { (split //)[$index] != $most_freq_bit  } @co2sr;
     52     @co2sr = @temp_co2sr; # replace real array with temporary array
     53     last if (scalar( @co2sr ) == 1);
     54 }
     55 
     56 # From the perlfunc man page:
     57 #        oct EXPR
     58 #        oct Interprets EXPR as an octal string and returns the corresponding
     59 #            value.  (If EXPR happens to start off with "0x", interprets it as a
     60 #            hex string.  If EXPR starts off with "0b", it is interpreted as a
     61 #            binary string.  Leading whitespace is ignored in all three cases.)
     62 say oct("0b" . join("", @ogr)) * oct("0b" . join("", @co2sr));