Advent of Code 2015 day 1 part 2: solved

This commit is contained in:
Fabian Tessmer 2025-03-21 22:20:03 +01:00
parent 5850103cb7
commit 325e726451
4 changed files with 48 additions and 19 deletions

File diff suppressed because one or more lines are too long

1
2015/day1/input.txt Normal file

File diff suppressed because one or more lines are too long

View File

@ -22,4 +22,15 @@ To what floor do the instructions take Santa?
Your puzzle answer was 232.
The first half of this puzzle is complete! It provides one gold star: *
--- 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?
Your puzzle answer was 1783.
Both parts of this puzzle are complete! They provide two gold stars: **

35
2015/day1/solution.py Normal file
View File

@ -0,0 +1,35 @@
import os
def get_floor(x: str) -> int:
ob = x.count("(")
cb = x.count(")")
return ob - cb
def get_first_char_to_basement(x: str) -> int:
current_floor = 0
for i, char in enumerate(x):
if char == '(':
current_floor += 1
elif char == ')':
current_floor -= 1
if current_floor < 0:
return i + 1
if __name__ == "__main__":
assert get_floor("(())") == 0 and get_floor("()()") == 0, "Error: Example 1 doesn't compute"
assert get_floor("(((") == 3 and get_floor("(()(()(") == 3, "Error: Example 2 doesn't compute"
assert get_floor("))(((((") == 3, "Error: Example 3 doesn't compute"
assert get_floor("())") == -1 and get_floor("))(") == -1, "Error: Example 4 doesn't compute"
assert get_floor(")))") == -3 and get_floor(")())())") == -3, "Error: Example 4 doesn't compute"
assert get_first_char_to_basement(")") == 1, "Error: Part2: Example 1 doesn't compute"
assert get_first_char_to_basement("()())") == 5, "Error: Part2: Example 2 doesn't compute"
puzzle_input = open("day1/input.txt", "r").readline()
print("Puzzle Input:", puzzle_input)
print("solution part1:", get_floor(puzzle_input))
print("solution part2:", get_first_char_to_basement(puzzle_input))