DEV Community

Ricardo Busquet
Ricardo Busquet

Posted on

Advent of Code 2021

                      ~   ~  ~ ~~ ~~~~~~~~~~~~~~~
                                           ..''''
Enter fullscreen mode Exit fullscreen mode

I'll be posting here my solutions for AoC 2021. Follow along!

--- Day 1: Sonar Sweep --- [link]

For part 1, we're given a list of numbers and are asked how many times the numbers increase relatively to the previous number. The solution is pretty straightforward: loop over the list, compare each item with the previous, count the occurrence where it's greater than the previous:

with open(Path(__file__).parent / "input.txt") as file:
    previous = int(file.readline())

    increases = 0
    for value in map(int, file):
        increases += value > previous
        previous = value
    return increases
Enter fullscreen mode Exit fullscreen mode

For part 2, we're asked to consider the sum of a three-measurement sliding window. I thought I would need a deque to keep a list of 3 values, or use list comprehension + slices, when I remembered about these recipes in the python docs. I copied over an implementation for a generator of these windows and used for my solution:

def sliding_window(iterable, n):
    # sliding_window('ABCDEFG', 4) -> ABCD BCDE CDEF DEFG
    it = iter(iterable)
    window = collections.deque(islice(it, n), maxlen=n)
    if len(window) == n:
        yield tuple(window)
    for x in it:
        window.append(x)
        yield tuple(window)

with open(Path(__file__).parent / "input.txt") as file:
    it = sliding_window(map(int, file), 3)
    previous = next(it)

    increases = 0
    for window in it:
        increases += sum(window) > sum(previous)
        previous = window
    return increases
Enter fullscreen mode Exit fullscreen mode

For the next days, I'm adding more-itertools to have these recipes readily available!

Check my repository for the final code for day 1. See y'all tomorrow!

Top comments (0)