/ domm

I hack Perl for fun and profit

Follow me on twitter!
Atom Icom ... on Atom!
<<<<<<<<<<
04.12.2020: Advent of Code Day 3 - the first modulo
03.12.2020: Advent of Code Day 2 - counting regex
03.12.2020: 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

Comments (via senph)

29.11.2020: My Advent of Code 2019
28.06.2020: Perl Conference in the Cloud report
18.06.2020: How to reclaim disk space used by docker (volumes), but keep a few important ones
29.03.2020: Perl Virtual Events?
29.03.2020: A very late German Perl Workshop 2020 report
04.03.2020: Perl Intro Curriculum
01.03.2020: YEF: shutdown -h
>>>>>>>>>>
<