Advent Of Code 2015: Day 1
The Challenge
--- Day 1: Not Quite Lisp ---
Santa was hoping for a white Christmas, but his weather machine's "snow" function is powered by stars, and he's fresh out! To save Christmas, he needs you to collect fifty stars by December 25th.
Collect stars by helping Santa solve puzzles. Two puzzles will be made available on each day in the advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!
Here's an easy puzzle to warm you up.
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?
--- Part Two ---
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?
Solution
Before part 2 of the problem was revealed I decided to tackle the problem using the command line. I cam up with the following command:
# Day 1 - Part 1
echo $((`cat input.txt | tr -d '\)' | wc -c` - `cat input.txt | tr -d '\(' | wc -c`))
We echo the input and remove the )
symbol which leaves only (
and we use wc
to count the number of (
symbols which tells us how many times we went to a higher floor. We then subtract his number from the number of times we went to a lower floor (using bash arithmetic) which gives us our answer.
Part 2 of the problem would be annoying to do on the command line so I decided to write a quick python script to solve it. The solution also solves the first part of the problem (lol).
counter = 0
level = 0
basement_pos = 1
basement_found = False
with open("input.txt", "r") as file:
for line in file:
for c in line:
if c == ')':
level -= 1
elif c == '(':
level += 1
counter += 1
# Check if in basement
if (level < 0 and not basement_found):
basement_pos = counter
basement_found = True
# Conclusion (we did part 1 too lol)
print "Final level:", level
print "First basement level position:", basement_pos