Advent of Code 2021 – Day 1: Sonar Sweep
Link to the Advent of Code Problem: https://adventofcode.com/2021/day/1
Language Used: Python
Efficiency: Part 1: O(n), Part 2: O(n)
Prework
Most of the Advent of Code data is served as a text file with newline separated data. This is our data loader, which we will use variants of for different days in the challenge:
stringData = open('day1_data.txt').read().split('\n')
data = []
for line in stringData:
data.append(int(line))
This will take the day1_data.txt
file, and load our input into an list called data
, as integers. This is important to do ahead of time for this day, as string and integer comparison can give differing results.
Part 1 – Iterative Comparison:
This is a fairly straightforward problem. We should simply iterate over the data, tracking the last value obtained, while incrementing a counter every time the new value exceeds the last value obtained.
# Part 1
lastMeasurement = 0
increaseCounter = 0
for measurement in data:
if measurement > lastMeasurement:
increaseCounter += 1
lastMeasurement = measurement
print(increaseCounter - 1)
We have to print increaseCounter - 1
instead of just increaseCounter
due to the comparison of the first value to a 0 value. We could also do this:
# Part 1
lastMeasurement = data[0]
increaseCounter = 0
for measurement in data[1:]:
if measurement > lastMeasurement:
increaseCounter += 1
lastMeasurement = measurement
print(increaseCounter)
This code should run fairly quickly. When ran with our time checker, usually this would run in milliseconds.
Part 2 – Sliding Window Sum Comparison:
The second part of this challenge is basically the same problem, with a catch! We need to track a sliding window of values. An easy way to do this is with slices. We will also have to consider a cursor, since we need to reference where we are within the data list.
With a cursor and the use of slices, we can express a sliding window as sum(data[cursor:cursor+3])
. This will cut a section of the list out, from position cursor
to cursor+3
, and then get the sum()
of the slice… this is our window!
It will also be easier in this case to use a while
loop, to better control the limits of the cursor. We can simply do this by using len()
. Since slices that attempt to reference past their limits only return what is available, we don’t need to pad this. For reference:
Python 3.9.13
>>> a = [1,2,3,4]
>>> a[0:44]
[1, 2, 3, 4]
In the example above, I attempted to get a slice larger than the list, and only the available data was returned. Since our data set does not contain negative numbers, having a window with less than 3 items in it will never increase our counter.
Here’s our solution:
# Part 2
oldWindow = 0
increaseCounter = 0
cursor = 0
while cursor < len(data):
if sum(data[cursor:cursor+3]) > oldWindow:
increaseCounter += 1
oldWindow = sum(data[cursor:cursor+3])
cursor += 1
print(increaseCounter - 1)
Conclusion
Thanks for reading! Look out for the next entries!