Skip to content

Instantly share code, notes, and snippets.

@mscha
Created December 7, 2024 14:20
Show Gist options
  • Select an option

  • Save mscha/a20b035c471624b4932820a990868cc1 to your computer and use it in GitHub Desktop.

Select an option

Save mscha/a20b035c471624b4932820a990868cc1 to your computer and use it in GitHub Desktop.
Advent of Code 2024 day 7 - using junctions
#!/usr/bin/env raku
use v6.d;
$*OUT.out-buffer = False; # Autoflush
# Advent of Code 2024 day 7 -- https://adventofcode.com/2024/day/7
sub infix:<∥>(Int $i, Int $j --> Int)
{
# Slightly faster than ($i~$j).Int
return 10*$i + $j if $j < 10;
return 100*$i + $j if $j < 100;
return 1000*$i + $j if $j < 1000;
return 10000*$i + $j if $j < 10000;
return 100000*$i + $j if $j < 100000;
return 1000000*$i + $j if $j < 1000000;
die "My head hurts, $j is too big!";
}
sub valid-equation($equation)
{
my ($value, @terms) = $equation.comb(/\d+/)».Int;
my $ans = @terms.shift;
for @terms -> $t {
$ans = $ans+$t | $ans*$t;
}
return $ans == $value ?? $value !! 0;
}
sub valid-equation-v2($equation)
{
my ($value, @terms) = $equation.comb(/\d+/)».Int;
my $ans = @terms.shift;
for @terms -> $t {
$ans = $ans+$t | $ans*$t | $ans∥$t;
}
return $ans == $value ?? $value !! 0;
}
sub MAIN(IO() $inputfile where *.f = 'aoc07.input', Bool :v(:$verbose) = False)
{
my @equations = $inputfile.lines;
say "Part 1: ", @equations».&valid-equation.sum;
say "Part 2: ", @equations».&valid-equation-v2.sum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment