Advent of Code 2020 - Day 1


Advent of Code 2020 - Day 1

If you’re like Linus Torvalds, and you just want me to show you the code, check it out here!

Intro

Another year, another Advent of Code. Last year, I fell off after day 14. This year will be different!

I’m going to tackle each day as soon as I can and post a short write-up about my solution.

Day 1

This one was pretty simple for me. It seems like they make sure to lob softballs for the first couple days. I think this is good design, because it gives people time to work out their dev environment (and get hooked on solving puzzles).

So, the task is to find which numbers in a list add up to another number (2020). Simple enough (especially if you’re into burning CPU cycles - I am).

My approach is to do nested loops to linearly search the list for the right combinations. There isn’t too much to say here, so I’ll just drop the code.

I could improve this by using indexes the whole way and avoiding slices - I believe each slice copies a list of references and it would be more efficient to do without.

def p_1(input_path: str) -> str:
    with open(input_path) as f:
        vals = [int(line) for line in f.readlines()]

    for ind1, val1 in enumerate(vals):
        for val2 in vals[ind1+1:]:
            if val1 + val2 == 2020:
                return str(val1 * val2)

    return "Couldn't solve this one"


def p_2(input_path: str) -> str:
    with open(input_path) as f:
        vals = [int(line) for line in f.readlines()]

    for ind1, val1 in enumerate(vals):
        for ind2, val2 in enumerate(vals[ind1+1:]):
            for val3 in vals[ind2+1:]:
                if val1 + val2 + val3 == 2020:
                    return str(val1 * val2 * val3)

    return "Couldn't solve this one"

As always, see the full repo here