This is a solution to Advent of Code 2020 day 15, written in Raku.
https://adventofcode.com/2020/day/15
Part One
Given your starting numbers, what will be the 2020th number spoken?
Raku
This a quick-n-dirty solution in Raku. I nearly messed up pushing the last starting input to the
%seen
list before considering it.
my @input = 2, 1, 10, 11, 0, 6;
my %seen;
my $last = @input.pop;
for ^@input.elems -> $i {
%seen{@input[$i]} = $i;
}
for @input.elems..^2019 -> $i {
my $new;
if %seen{$last}:exists {
$new = $i - %seen{$last};
} else {
$new = 0;
}
%seen{$last} = $i;
$last = $new;
}
say $last;
232
Part Two
Given your starting numbers, what will be the 30000000th number spoken?
Raku
The solution to part one was efficient enough that it worked for part two as well. A bit slow to run but manageable.
my @input = 2, 1, 10, 11, 0, 6;
my %seen;
my $last = @input.pop;
for ^@input.elems -> $i {
%seen{@input[$i]} = $i;
}
for @input.elems..^(30000000-1) -> $i {
my $new;
if %seen{$last}:exists {
$new = $i - %seen{$last};
} else {
$new = 0;
}
%seen{$last} = $i;
$last = $new;
}
say $last;
18929178