solve Day12 Part1 in python

This commit is contained in:
WieErWill 2023-12-12 18:12:55 +01:00
parent bf97872f92
commit 5fe2e22a49
4 changed files with 190 additions and 1 deletions

74
Day12/README.md Normal file
View File

@ -0,0 +1,74 @@
# Day 12: Hot Springs
## Part One
You finally reach the hot springs! You can see steam rising from secluded areas attached to the primary, ornate building.
As you turn to enter, the researcher stops you. "Wait - I thought you were looking for the hot springs, weren't you?" You indicate that this definitely looks like hot springs to you.
"Oh, sorry, common mistake! This is actually the onsen! The hot springs are next door."
You look in the direction the researcher is pointing and suddenly notice the massive metal helixes towering overhead. "This way!"
It only takes you a few more steps to reach the main gate of the massive fenced-off area containing the springs. You go through the gate and into a small administrative building.
"Hello! What brings you to the hot springs today? Sorry they're not very hot right now; we're having a lava shortage at the moment." You ask about the missing machine parts for Desert Island.
"Oh, all of Gear Island is currently offline! Nothing is being manufactured at the moment, not until we get more lava to heat our forges. And our springs. The springs aren't very springy unless they're hot!"
"Say, could you go up and see why the lava stopped flowing? The springs are too cold for normal operation, but we should be able to find one springy enough to launch you up there!"
There's just one problem - many of the springs have fallen into disrepair, so they're not actually sure which springs would even be safe to use! Worse yet, their condition records of which springs are damaged (your puzzle input) are also damaged! You'll need to help them repair the damaged records.
In the giant field just outside, the springs are arranged into rows. For each row, the condition records show every spring and whether it is operational (.) or damaged (#). This is the part of the condition records that is itself damaged; for some springs, it is simply unknown (?) whether the spring is operational or damaged.
However, the engineer that produced the condition records also duplicated some of this information in a different format! After the list of springs for a given row, the size of each contiguous group of damaged springs is listed in the order those groups appear in the row. This list always accounts for every damaged spring, and each number is the entire size of its contiguous group (that is, groups are always separated by at least one operational spring: #### would always be 4, never 2,2).
So, condition records with no unknown spring conditions might look like this:
```
#.#.### 1,1,3
.#...#....###. 1,1,3
.#.###.#.###### 1,3,1,6
####.#...#... 4,1,1
#....######..#####. 1,6,5
.###.##....# 3,2,1
```
However, the condition records are partially damaged; some of the springs' conditions are actually unknown (?). For example:
```
???.### 1,1,3
.??..??...?##. 1,1,3
?#?#?#?#?#?#?#? 1,3,1,6
????.#...#... 4,1,1
????.######..#####. 1,6,5
?###???????? 3,2,1
```
Equipped with this information, it is your job to figure out how many different arrangements of operational and broken springs fit the given criteria in each row.
In the first line (???.### 1,1,3), there is exactly one way separate groups of one, one, and three broken springs (in that order) can appear in that row: the first three unknown springs must be broken, then operational, then broken (#.#), making the whole row #.#.###.
The second line is more interesting: .??..??...?##. 1,1,3 could be a total of four different arrangements. The last ? must always be broken (to satisfy the final contiguous group of three broken springs), and each ?? must hide exactly one of the two broken springs. (Neither ?? could be both broken springs or they would form a single contiguous group of two; if that were true, the numbers afterward would have been 2,3 instead.) Since each ?? can either be #. or .#, there are four possible arrangements of springs.
The last line is actually consistent with ten different arrangements! Because the first number is 3, the first and second ? must both be . (if either were #, the first number would have to be 4 or higher). However, the remaining run of unknown spring conditions have many different ways they could hold groups of two and one broken springs:
```
?###???????? 3,2,1
.###.##.#...
.###.##..#..
.###.##...#.
.###.##....#
.###..##.#..
.###..##..#.
.###..##...#
.###...##.#.
.###...##..#
.###....##.#
```
In this example, the number of possible arrangements for each row is:
- ???.### 1,1,3 - 1 arrangement
- .??..??...?##. 1,1,3 - 4 arrangements
- ?#?#?#?#?#?#?#? 1,3,1,6 - 1 arrangement
- ????.#...#... 4,1,1 - 1 arrangement
- ????.######..#####. 1,6,5 - 4 arrangements
- ?###???????? 3,2,1 - 10 arrangements
Adding all of the possible arrangement counts together produces a total of 21 arrangements.
For each row, count all of the different arrangements of operational and broken springs that meet the given criteria. What is the sum of those counts?

109
Day12/python/solution1.py Normal file
View File

@ -0,0 +1,109 @@
def parse_line(line):
"""
Parse a line into spring states and group sizes.
"""
try:
parts = line.strip().split()
states = parts[0]
group_sizes = [int(x) for x in parts[1].split(',')]
return states, group_sizes
except Exception as e:
print(f"Error parsing line '{line}': {e}")
raise
def is_valid_configuration(states, group_sizes):
"""
Check if a given configuration of springs is valid based on group sizes.
"""
try:
i, size_index = 0, 0
while i < len(states):
if states[i] == '#':
if size_index >= len(group_sizes):
return False # More broken springs than groups
count = 0
while i < len(states) and states[i] == '#':
count += 1
i += 1
if count != group_sizes[size_index]:
return False # Group size mismatch
size_index += 1
else:
i += 1
return size_index == len(group_sizes) # All groups must be accounted for
except Exception as e:
print(f"Error in is_valid_configuration: {e}")
raise
def count_configurations(states, group_sizes, index=0, memo=None):
"""
Count the number of valid configurations using backtracking and memoization.
"""
if memo is None:
memo = {}
key = (tuple(states), index)
if key in memo:
return memo[key]
if index == len(states):
memo[key] = 1 if is_valid_configuration(states, group_sizes) else 0
return memo[key]
if states[index] != '?':
memo[key] = count_configurations(states, group_sizes, index + 1, memo)
return memo[key]
count = 0
for state in ['.', '#']:
states[index] = state
count += count_configurations(states, group_sizes, index + 1, memo)
states[index] = '?'
memo[key] = count
return count
def solve_puzzle(file_path):
"""
Solve the puzzle for each line in the file and return the total count of configurations.
"""
try:
total_count = 0
with open(file_path, 'r') as file:
for line in file:
states, group_sizes = parse_line(line)
count = count_configurations(list(states), group_sizes)
total_count += count
print(f"Line: {line.strip()}, Possible Configurations: {count}")
return total_count
except Exception as e:
print(f"Error in solve_puzzle: {e}")
raise
def test():
"""
Test the solution with a test file.
"""
print("Running tests...")
test_result = solve_puzzle("../test.txt")
print(f"Test Result: {test_result}")
assert test_result == 21, f"Test failed, expected 21, got {test_result}"
print("Test passed successfully.")
def main():
"""
Main function to run the test and then solve the puzzle.
"""
try:
test()
result = solve_puzzle("../input.txt")
print(f"Final Result: {result}")
except Exception as e:
print(f"Error in main: {e}")
raise
if __name__ == "__main__":
main()

6
Day12/test.txt Normal file
View File

@ -0,0 +1,6 @@
???.### 1,1,3
.??..??...?##. 1,1,3
?#?#?#?#?#?#?#? 1,3,1,6
????.#...#... 4,1,1
????.######..#####. 1,6,5
?###???????? 3,2,1

View File

@ -45,7 +45,7 @@ I aim to complete each day's puzzle on the same day, but as with any challenge,
| 09 | ✅ | ✅ | [Day09 README](/Day09/README.md) |
| 10 | ✅ | ✅ | [Day10 README](/Day10/README.md) |
| 11 | ✅ | ✅ | [Day11 README](/Day11/README.md) |
| 12 | | ❓ | [Day12 README](/Day12/README.md) |
| 12 | | ❓ | [Day12 README](/Day12/README.md) |
| 13 | ❓ | ❓ | [Day13 README](/Day13/README.md) |
| 14 | ❓ | ❓ | [Day14 README](/Day14/README.md) |
| 15 | ❓ | ❓ | [Day15 README](/Day15/README.md) |