Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use strict;
- use warnings;
- use feature qw(say);
- use List::Util qw(sum product zip);
- sub chain (&@) {
- my $block = shift;
- return (map { &$block( $_[$_-1], $_[$_] ) } (1 .. $#_));
- }
- # Read input:
- my @input = <>;
- my @ops = map { split /\s+/ } pop @input;
- # Find space delimiters (those shared by all lines)
- my %spaces;
- foreach (@input) {
- $spaces{pos($_)}++ while (m/\s/g);
- }
- my @spaces = sort {$a<=>$b} grep { $spaces{$_} == @input } keys %spaces;
- # Do calculation:
- my $part2 = 0;
- foreach my $width (chain {$_[1] - $_[0]} (0, @spaces)) {
- # Grab next numbers with the trailing space delimiter
- my @horz = map { [split //, substr( $_, 0, $width, '' )] } @input;
- my @vert = grep { m#\d# } map { join( '', @$_ ) } zip @horz;
- $part2 += (shift @ops eq '+') ? sum @vert : product @vert;
- }
- say "Part 2: $part2";
Advertisement
Add Comment
Please, Sign In to add comment