Advertisement
musifter

AoC 2023 day 9 both parts (Perl)

Dec 9th, 2023
725
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 0.63 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use v5.26;
  4. use warnings;
  5.  
  6. use List::Util      qw(all sum reduce);
  7.  
  8. sub chain (&@) {
  9.     my $block = shift;
  10.     return (map { &$block( $_[$_-1], $_[$_] ) } (1 .. $#_));
  11. }
  12.  
  13. my @input = map { [m#([-0-9]+)#g] } <>;
  14.  
  15. my $part1 = 0;
  16. my $part2 = 0;
  17. foreach my $list (@input) {
  18.     my @table = ($list);
  19.  
  20.     my $i = 0;
  21.     do {
  22.         $i++;
  23.         $table[$i] = [chain { $_[1] - $_[0] } $table[$i-1]->@*];
  24.     } until (all { $_ == 0 } $table[$i]->@*);
  25.  
  26.     $part1 += sum map { $_->[-1] } @table;
  27.     $part2 += reduce { $b - $a } reverse map { $_->[0] } @table;
  28. }
  29.  
  30. say "Part 1: $part1";
  31. say "Part 2: $part2";
  32.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement