Day 1: Sonar Sweep
Well… let’s save the Christmas again, in a submarine… ¯\_(ツ)_/¯
.
The first problem is about to help the sub crew to check how quickly the depth increases. We have the sonar sweep report (our puzzle input) appears: each line is a measurement of the sea floor depth as the sweep looks further and further away from the submarine. And to do this, count the number of times a depth measurement increases from the previous measurement. (There is no measurement before the first measurement.)
Crunching numbers
After loading the input, we can solve it with just 1 line of Python code:
I sove this using list comprehension (again). I created a zip
object from the original list. A zip object is a list of tuples and for this case the first element of the tuple is the list item, the second element of the tuple is the next list item (using the [1:]
notation).
The list comprehension is easy, just create a new list, containing bol
object True
if item < next_item
. To create the item
and next_item
variables, just extract the first and second item for each zip object tuple. And just print how many itens on the new list, we know if we are getting down.
Too much noise!
Well, in the Advent of Code fashion, what if better than one problem? Two problems. So, now we have to check if the are getting down, but consider sums of a *three-measurement sliding window. *We have to compare the sum of current measurement and next two measurements with the sum of next measurement and its next two measurements and count how many times the sum of measurements in this sliding window increases. Complicated? Let-me draw it (I mean, copy the problem text).
1199 A
2200 A B
3208 A B C
4210 B C D
5200 E C D
6207 E F D
7240 E F G
8269 F G H
9260 G H
10263 H
Start by comparing the first and second three-measurement windows. The measurements in the first window are marked A
(199
, 200
, 208
); their sum is 199 + 200 + 208 = 607
. The second window is marked B
(200
, 208
, 210
); its sum is 618
. The sum of measurements in the second window is larger than the sum of the first, so this first comparison increased.
Again, list comprehension gonna save the day.
1sums = [sum(tuple_item) for tuple_item in zip(line_list, line_list[1:], line_list[2:])]
2print(len([True for item, next_item in zip(sums, sums[1:]) if item < next_item]))
First, create a list with the three-measurement sliding window, by creating list containing the sum of all tuple elements from a zip object with item[n], item[n+1] and item[n+2]
. With this list, just apply the same list comprehension of the first problem, and done. Just print how many itens on the new list, we know if we are getting down, without noise.
Day 1 done, 2 start to my account.
Happy Advent of Code
Z
Comments