Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use strict;
- use warnings;
- use List::AllUtils qw(indexes none min product);
- sub inc (@) {
- return (map {$_ + 1} @_);
- }
- #
- # Packet comparison (recursive)
- #
- sub cmp_packet {
- my @pack = @_;
- # Handle base case of two integers:
- return ($pack[0] <=> $pack[1]) if (none { ref } @pack);
- # List comparisons (first promote if needed)
- @pack = map { !ref ? [$_] : $_ } @pack;
- # Try elements up to size of smaller list:
- my $minlen = min map { scalar @$_ } @pack;
- for (my $i = 0; $i < $minlen; $i++) {
- my $ret = &cmp_packet( $pack[0][$i], $pack[1][$i] );
- return ($ret) if ($ret != 0);
- }
- # Finally, compare sizes of lists:
- return ($pack[0]->@* <=> $pack[1]->@*);
- }
- #
- # Part 1
- #
- my @input = map {$_ ? eval($_) : undef} <>;
- my $part1 = 0;
- for (my $i = 1; $i <= @input / 2; $i++) {
- my $left = $input[2*$i - 2];
- my $right = $input[2*$i - 1];
- $part1 += $i if (&cmp_packet( $left, $right ) < 0);
- }
- print "Part 1: $part1\n";
- #
- # Part 2
- #
- my @markers = ([[2]], [[6]]);
- push( @input, @markers );
- my $part2 = product inc indexes {
- my $packet = $_;
- grep { $_ == $packet } @markers
- } sort {&cmp_packet( $a, $b )} @input;
- print "Part 2: $part2\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement