logo

adventofcode

Code used to solve https://adventofcode.com/, one branch per year git clone https://anongit.hacktivis.me/git/adventofcode.git/

day1_part2.pl (821B)


  1. #!/usr/bin/env perl
  2. # SPDX-FileCopyrightText: 2023 Haelwenn (lanodan) Monnier <contact+aoc2023@hacktivis.me>
  3. # SPDX-License-Identifier: MIT
  4. use strict;
  5. my $base = qr<(one|two|three|four|five|six|seven|six|seven|eight|nine|[0-9])>;
  6. sub traa {
  7. ($_) = @_;
  8. $_ =~ s/one/1/;
  9. $_ =~ s/two/2/;
  10. $_ =~ s/three/3/;
  11. $_ =~ s/four/4/;
  12. $_ =~ s/five/5/;
  13. $_ =~ s/six/6/;
  14. $_ =~ s/seven/7/;
  15. $_ =~ s/eight/8/;
  16. $_ =~ s/nine/9/;
  17. return $_;
  18. }
  19. my $total = 0;
  20. while(my $line = <>) {
  21. chomp( $line );
  22. print "$line ";
  23. # .*? for non-greedy / smallest matching
  24. my $first = traa($line =~ qr<^.*?${base}>);
  25. # For some reason it needs .* at the start
  26. my $last = traa($line =~ qr<.*${base}.*?$>);
  27. print "($first | $last)";
  28. my $val = int($first.$last);
  29. print "= ", $val, "\n";
  30. $total += $val;
  31. }
  32. print "Total: ", $total, "\n";