#!/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> ) ); # Advent of Code 2021 Day 03 Part 2 my $len = length($input[0]) - 1; # number of bits - 1 my @ogr = @input; foreach my $index (0 .. $len) { # first iterate through indices... my $count; foreach my $line (@ogr) { # ...and then through the numbers/lines if ( (split //, $line)[$index] ) { # if bit at position $index is 1 $count++; # postive or zero count means 1 } else { $count--; # negative count means 0 } } # now see which is the most common bit at the index # if $count < 0, it's 0; otherwise it's 1 my $most_freq_bit = ($count < 0) ? 0 : 1; my @temp_ogr = grep { (split //)[$index] == $most_freq_bit } @ogr; @ogr = @temp_ogr; # replace real array with temporary array last if (scalar( @ogr ) == 1); } my @co2sr = @input; foreach my $index (0 .. $len) { # first iterate through indices... my $count; foreach my $line (@co2sr) { # ...and then through the numbers/lines if ( (split //, $line)[$index] ) { # if bit at position $index is 1 $count++; # postive or zero count means 1 } else { $count--; # negative count means 0 } } # now see which is the most common bit at the index # if $count < 0, it's 0; otherwise it's 1 my $most_freq_bit = ($count < 0) ? 0 : 1; my @temp_co2sr = grep { (split //)[$index] != $most_freq_bit } @co2sr; @co2sr = @temp_co2sr; # replace real array with temporary array last if (scalar( @co2sr ) == 1); } # 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" . join("", @ogr)) * oct("0b" . join("", @co2sr));