Advertisement
musifter

AoC 2024 day 13 (Perl)

Dec 13th, 2024 (edited)
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.13 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use feature         qw(say);
  7.  
  8. use constant  X => 0;
  9. use constant  Y => 1;
  10.  
  11. use constant  A_COST => 3;
  12. use constant  B_COST => 1;
  13.  
  14. sub solve_cost {
  15.     my ($a, $b, $target) = @_;
  16.  
  17.     my $a_numer = $target->[X] * $b->[Y] - $target->[Y] * $b->[X];
  18.     my $b_numer = $target->[Y] * $a->[X] - $target->[X] * $a->[Y];
  19.  
  20.     my $denom   = $a->[X] * $b->[Y] - $a->[Y] * $b->[X];
  21.  
  22.     # Test for integer solution
  23.     if ($a_numer % $denom == 0 and $b_numer % $denom == 0) {
  24.         return (A_COST * $a_numer / $denom + B_COST * $b_numer / $denom);
  25.     }
  26.  
  27.     return (0);
  28. }
  29.  
  30. my $part1 = 0;
  31. my $part2 = 0;
  32.  
  33. $/ = '';    # Paragraph mode, 1 machine per paragraph
  34.  
  35. foreach my $machine (map {[split /\n/]} <>) {
  36.     my @a_move = ($machine->[0] =~ m#(\d+)#g);
  37.     my @b_move = ($machine->[1] =~ m#(\d+)#g);
  38.     my @target = ($machine->[2] =~ m#(\d+)#g);
  39.  
  40.     my @target2 = map { $_ + 10_000_000_000_000 } @target;
  41.  
  42.     $part1 += &solve_cost( \@a_move, \@b_move, \@target );
  43.     $part2 += &solve_cost( \@a_move, \@b_move, \@target2 );
  44. }
  45.  
  46. say "Part 1: $part1";
  47. say "Part 2: $part2";
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement