Advertisement
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 constant X => 0;
- use constant Y => 1;
- use constant A_COST => 3;
- use constant B_COST => 1;
- sub solve_cost {
- my ($a, $b, $target) = @_;
- my $a_numer = $target->[X] * $b->[Y] - $target->[Y] * $b->[X];
- my $b_numer = $target->[Y] * $a->[X] - $target->[X] * $a->[Y];
- my $denom = $a->[X] * $b->[Y] - $a->[Y] * $b->[X];
- # Test for integer solution
- if ($a_numer % $denom == 0 and $b_numer % $denom == 0) {
- return (A_COST * $a_numer / $denom + B_COST * $b_numer / $denom);
- }
- return (0);
- }
- my $part1 = 0;
- my $part2 = 0;
- $/ = ''; # Paragraph mode, 1 machine per paragraph
- foreach my $machine (map {[split /\n/]} <>) {
- my @a_move = ($machine->[0] =~ m#(\d+)#g);
- my @b_move = ($machine->[1] =~ m#(\d+)#g);
- my @target = ($machine->[2] =~ m#(\d+)#g);
- my @target2 = map { $_ + 10_000_000_000_000 } @target;
- $part1 += &solve_cost( \@a_move, \@b_move, \@target );
- $part2 += &solve_cost( \@a_move, \@b_move, \@target2 );
- }
- say "Part 1: $part1";
- say "Part 2: $part2";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement