Pages

2021/12/01

Advent of Code 2021 - Day 1

This is a running series of posts on the Advent of Code 2020. The introductory post has the details, including the accompanying GitHub repo, in case you reached this directly.

This year's first exercise is quite straightforward. The input is a sequence of numbers.

Part 1

The task is to count how many of the numbers in the input are greater than the previous one. Using indexes, we could build a generator of the differences as:

diffs = (numbers[idx+1] - numbers[idx] for idx in range(len(numbers) - 1)

But this looks more like C than Python. We will avoid the indexing by zipping together the sequence and a shifted version:

diffs = (succ - pred for pred, succ in zip(numbers, numbers[1:]))

Then it's just a matter of filtering the positive differences and counting them.

Part 2

For the second part we only have to count the increasing numbers over a smoothed version of the sequence, a moving average of sorts (actually the sum of the rolling window, without dividing by its size). That means that it's only necessary to preprocess the numbers sequence.

The only point that needs some care is to ensure that the new sequence is of the right length: we are calculating sum(numbers[idx : idx + window]) for all indices idx from 0 to len(numbers) - window (including the last one, so the end of the range is that + 1). Stop before and not all possible windows will be included; stop later, and windows of smaller size at the end of the list will be included: the mistake will not cause an error, as slicing silently ignores indices beyond the end.

Luckily for those who make the mistake of going beyond the right index, with all the numbers being positive the extra windows will never increase compared to the one before, so the answer will actually be right. By stopping short it is possible to get the wrong answer, but only if the last window was increasing.

No comments:

Post a Comment