AoC 2021 - Day 1

First day of the Advent of Code turned out to be pretty easy, the first task was to find the number of consecutive increases in the sequence of numbers. The simplest way to do it would be to use a simple loop to compare each number with the one before it.

Task 1

In my solution however I took a different approach - I sliced the sequence, so that there’s two of them and they’re offset by 1. I then used the zip function to zip the values together into tuples of the form (previous, current). Then I used a generator to compare the values in tuple, which outputs True if current is greater than previous and False otherwise. Then I summed the resulting sequence of booleans… You can do that? In Python yes, because True is 1 and False is 0.

def solve1() -> int:
    with open('../.input/day01', 'r') as f:
        numbers: list[int] = [int(line) for line in f.readlines()]
    return sum((n > p) for p, n in zip(numbers[:-1], numbers[1:]))

Task 2

In the second task I used the same approach, but this time I zipped 3 consecutive elements together to form a window tuple. Then I zipped another 3, but this time offset by 1. Then I zipped both of them together and used the sum function to sum the values of the tuples. The rest is analogous to the first task.

def solve2() -> int:
    with open('../.input/day01', 'r') as f:
        numbers: list[int] = [int(line) for line in f.readlines()]
    return sum((sum(n) > sum(p)) for p, n in zip(
        zip(numbers[:-3], numbers[1:-2], numbers[2:-1]),
        zip(numbers[1:-2], numbers[2:-1], numbers[3:])
    ))

Overall this task was pretty easy, but the second task took me a bit longer, I didn’t really get what I was supposed to do at first 😄