aoc2021

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

commit 64765fdf766b36b62669f840d6aa2864039c5d61
parent 750d7c759650bbd6cd4deae54089c87149705de4
Author: Samir Parikh <noreply@samirparikh.com>
Date:   Fri,  3 Dec 2021 15:38:01 +0000

Merge branch 'dev'

Diffstat:
Aday03.pl | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 52 insertions(+), 0 deletions(-)

diff --git a/day03.pl b/day03.pl @@ -0,0 +1,52 @@ +#!/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);