aoc2021

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

day03-1.pl (1509B) - 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 1
     18 my $len = length($input[0]) - 1; # number of bits - 1
     19 my $gamma_rate   = "";
     20 my $epsilon_rate = "";
     21 
     22 foreach my $index (0 .. $len) { # first iterate through indices...
     23     my $count;
     24     foreach my $line (@input) { # ...and then through the numbers/lines
     25         if ( (split //, $line)[$index] ) { # if bit at position $index is 1
     26             $count++; # postive or zero count means 1
     27         } else {
     28             $count--; # negative count means 0
     29         }
     30     }
     31     # now see which is the most common bit at the index
     32     if ($count < 0) { # most common bit at index is 0
     33         $gamma_rate   .= "0";
     34         $epsilon_rate .= "1";
     35     } else {          # most common bit at index is 1
     36         $gamma_rate   .= "1";
     37         $epsilon_rate .= "0";
     38     }
     39 }
     40 
     41 # From the perlfunc man page:
     42 #        oct EXPR
     43 #        oct Interprets EXPR as an octal string and returns the corresponding
     44 #            value.  (If EXPR happens to start off with "0x", interprets it as a
     45 #            hex string.  If EXPR starts off with "0b", it is interpreted as a
     46 #            binary string.  Leading whitespace is ignored in all three cases.)
     47 say oct("0b" . $gamma_rate) * oct("0b" . $epsilon_rate);