Advent Of Code 2021 - Day 01

Advent of Code 2021 - Day 01: Sonar Sweep

The 2020 Covid-Edition of the Advent of Code, was the first year where I completed all 50 stars. As the days are slowly becoming shorter and colder, I think it’s a good idea trying to complete the previous years as coding practice and a preparation for this year’s AoC.

Day 01: Not quite Lisp

Part 1

Day 01 is a very easy puzzle to warm you up.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
Santa is trying to deliver presents in a large apartment building, but he can't find the right floor - 
the directions he got are a little confusing. He starts on the ground floor (floor 0) and then follows the instructions one character at a time.

An opening parenthesis, (, means he should go up one floor, and a closing parenthesis, ), means he should go down one floor.  

The apartment building is very tall, and the basement is very deep; he will never find the top or bottom floors.

For example:

(()) and ()() both result in floor 0.
((( and (()(()( both result in floor 3.
))((((( also results in floor 3.
()) and ))( both result in floor -1 (the first basement level).
))) and )())()) both result in floor -3.
To what floor do the instructions take Santa?

We simply have to parse the input, and every ( will bring Santa one level up, every ) one level down. I try to solve these puzzles in a more pythonic style.

1
2
3
# part1
    nP = [1 if c=="(" else -1 for c in lines[0]]
    part1 = sum(nP)

Using list comprehension, the list of brackets is converted to the according numeric value for the change of floor. The solution to the first part is the sum of all these changes.

Part 2

1
2
3
4
5
6
7
8
Now, given the same instructions, find the position of the first character that causes him to enter the basement (floor -1). 
The first character in the instructions has position 1, the second character has position 2, and so on.

For example:

) causes him to enter the basement at character position 1.
()()) causes him to enter the basement at character position 5.
What is the position of the character that causes Santa to first enter the basement?

Now we have to find the first time Santa reaches the basement (level -1) . Using the list of part 1, we can compute the floor Santa reaches at each step using the partial sums, which itertools.accumulate accomplishes.

1
2
3
4
5
 # part1 & 2
    nP = [1 if c=="(" else -1 for c in lines[0]]
    aP = list(accumulate(nP))
    part1 = aP[-1]
    part2 = aP.index(-1)+1

As the last entry of the accumulated sums equals the total sum of the list, the sum(np) can be omitted.