Advent of Code Day 1 - brute loops
I'll write about by Advent of Code 2020 solutions here. Let's see how long I'll manage to particiate, and how big my blog-lag will be...
Part 1
Straight forward, brute force solution, with a tiny bit of smartness. I remove each element after checking it in the inner loop, because additions are commutative.
my @exp = ( <STDIN> );
while (my $a = shift (@exp)) {
for my $b (@exp) {
if ($a + $b == 2020) {
die $a*$b."\n";
}
}
}
I use die
with a sting ending with a newline for a shorter print () && exit
But I did not know about the trick where you store the values in a hash and then go through the hash, subtract the value from 2020 and look for an entry in the hash with the result. Maybe it's clearer in code:
my %data = map { chomp; $_=>1 } ( <STDIN> );
for my $a (keys %data) {
my $b = 2020 - $a;
if ($data{2020 - $a}) {
die $a*$b."\n";
}
}
Presumably this is a lot faster, but with this small data set, it makes no difference.
Part 2
As the data set is so small, I didn't even consider an smartness and just added another loop. This means we're in O(n^3) territory, but with a runtime of 0.2sec I just don't care...
my @exp = ( <STDIN> );
while (my $a = shift (@exp)) {
for my $b (@exp) {
for my $c (@exp) {
if ($a + $b +$c == 2020) {
say $a*$b*$c;
exit;
}
}
}
}
Oh, and here I did do say && exit
(even in two statements...)
Look Ma, no spaces!
Here's the same code, slightly golfed:
@d=<STDIN>;for$a(@d){for$b(@d){for$c(@d){die$a*$b*$c."\n"if$a+$b+$c==2020}}}
Stats & Links
- Time: ~5:00 / 5:39
- Rank: 11236 / 10430
- https://adventofcode.com/2020/day/1
- https://github.com/domm/adventofcode2020