Advertisement
musifter

AoC day 2, Perl (matrix)

Dec 2nd, 2021 (edited)
1,766
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.01 KB | None | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use List::AllUtils  qw(pairwise sum);
  7.  
  8. #
  9. # The calculation of a step is pos = pos + (vec * matrix).
  10. # With the center of the matrix set to aim for next.
  11. #
  12. # pos is (x, y, a), matrix is [ 1 0 0 ]
  13. #                             [ 0 a 0 ]
  14. #                             [ 0 0 1 ]
  15. #
  16. # vec is (m, m, 0) for forward, (0, 0, +/-m) for down/up
  17. #
  18. my @matrix = ([1, 0, 0],
  19.               [0, 0, 0],
  20.               [0, 0, 1]);
  21.  
  22. my @pos = (0, 0, 0);
  23.  
  24. while (<>) {
  25.     my ($cmd, $mag) = m#^(\w)\w+ (\d+)#;
  26.  
  27.     # scalar * vector using map
  28.     my @vec  = map { $mag * $_ } ('f' eq $cmd, 'f' eq $cmd, 'f' cmp $cmd);
  29.  
  30.     # vector * matrix with map-sum-pairwise
  31.     my @prod = map { sum pairwise { $a * $b } @vec, @$_ } @matrix;
  32.  
  33.     # vector + vector with pairwise
  34.     @pos = pairwise { $a + $b } @pos, @prod;
  35.  
  36.     # set center value of matrix to aim
  37.     $matrix[1][1] = $pos[2];
  38. }
  39.  
  40. print "Part 1: ", $pos[0] * $pos[2], "\n";
  41. print "Part 2: ", $pos[0] * $pos[1], "\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement