Skip to content

Instantly share code, notes, and snippets.

@lucasbuchala
Created December 2, 2019 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucasbuchala/528aec8565b101d9781db8f79e89f473 to your computer and use it in GitHub Desktop.
Save lucasbuchala/528aec8565b101d9781db8f79e89f473 to your computer and use it in GitHub Desktop.
Advent of Code 2019
use strict;
use warnings;
use feature qw(say);
use My::List::Numeric qw(sum);
sub f { int($_[0] / 3) - 2 }
sub g {
my $n = f($_[0]);
return $n > 0 ? $n + g($n) : 0;
}
sub main {
my @i = map int, <STDIN>;
say sum map f($_), @i;
say sum map g($_), @i;
}
main if not defined caller;
1;
use strict;
use warnings;
use feature qw(say);
sub run {
my ($arr, $i) = @_;
$i //= 0;
while (1) {
die "Index out of range" if $i < 0 or $i >= @$arr;
my $op = $arr->[$i];
my ($x, $y, $out) = @{$arr}[$i+1..$i+3];
if ($op == 1) { $arr->[$out] = $arr->[$x] + $arr->[$y] }
elsif ($op == 2) { $arr->[$out] = $arr->[$x] * $arr->[$y] }
elsif ($op == 99) { last }
else { die "Unexpected op=$op" }
$i += 4;
}
}
sub f {
my ($x, $y, @list) = @_;
$list[1] = $x;
$list[2] = $y;
run \@list;
return $list[0];
}
sub main {
my $input = do { local $/; <STDIN> };
my @list = map int, split /\s*,\s*/, $input;
for my $x (0..99) {
for my $y (0..99) {
if (f($x, $y, @list) == 19690720) {
say $x * 100 + $y;
}
}
}
}
main if not defined caller;
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment