add 2024/day19.1
This commit is contained in:
parent
ef0d905e29
commit
b8f58fdfa5
1 changed files with 51 additions and 0 deletions
51
2024/19/main.py
Normal file
51
2024/19/main.py
Normal file
|
@ -0,0 +1,51 @@
|
||||||
|
#!/usr/bin/env python
|
||||||
|
# -*- encoding: utf-8; py-indent-offset: 4 -*-
|
||||||
|
|
||||||
|
# Author: Sebastian Mark, Christian Hennevogl
|
||||||
|
# CC-BY-SA (https://creativecommons.org/licenses/by-sa/4.0/deed.de)
|
||||||
|
|
||||||
|
# pylint: disable=missing-module-docstring,missing-function-docstring,consider-using-f-string
|
||||||
|
|
||||||
|
|
||||||
|
def readinput():
|
||||||
|
with open("input", "r", encoding="utf-8") as file:
|
||||||
|
lines = file.readlines()
|
||||||
|
towels = [pattern.strip() for pattern in lines[0].split(",")]
|
||||||
|
designs = list(map(str.strip, lines[2:]))
|
||||||
|
return towels, designs
|
||||||
|
|
||||||
|
|
||||||
|
# pylint: disable-next=inconsistent-return-statements
|
||||||
|
def check_design(design: str, towels: list, cache=None) -> bool:
|
||||||
|
if cache is None:
|
||||||
|
cache = {}
|
||||||
|
|
||||||
|
if design in cache: # Check if the result for the current design is already cached.
|
||||||
|
return cache[design]
|
||||||
|
|
||||||
|
if not design: # Base case: empty design means it was successfully constructed.
|
||||||
|
return True
|
||||||
|
|
||||||
|
for towel in towels:
|
||||||
|
if design.startswith(towel): # Check if the design starts with the towel.
|
||||||
|
if check_design(design.removeprefix(towel), towels, cache):
|
||||||
|
cache[design] = True
|
||||||
|
return True
|
||||||
|
|
||||||
|
cache[design] = False # Cache the result as False if no valid combination is found.
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
towels, designs = readinput()
|
||||||
|
|
||||||
|
# part 1
|
||||||
|
sorted_towels = sorted(towels, key=len, reverse=True)
|
||||||
|
count = 0
|
||||||
|
for design in designs:
|
||||||
|
if check_design(design, sorted_towels):
|
||||||
|
count += 1
|
||||||
|
print("\nPossible designs: %d" % count)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
Loading…
Reference in a new issue