Browse Source

Bene do stuff

pull/1/head
Maya Herrscher 1 year ago
parent
commit
312113ce81
  1. 55
      2023/day12/code.py

55
2023/day12/code.py

@ -1,17 +1,14 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import sys import sys
import regex as re
from itertools import combinations
from more_itertools import locate
def memo(f): def memo(f):
memo = {} memo = {}
def f2(x,y): def f2(x,y):
if (x,y) not in memo: memo[(x,y)] = f(x,y) if (x,tuple(y)) not in memo: memo[(x,tuple(y))] = f(x,tuple(y))
return memo[(x,y)] return memo[(x,tuple(y))]
return f2 return f2
@ -19,37 +16,26 @@ def fulfills(spring, cond):
return [len(b) for b in spring.split('.') if len(b) > 0] == cond return [len(b) for b in spring.split('.') if len(b) > 0] == cond
def solve_row1(spring, cond): def dot(spring, cond):
if len(spring) == (sum(cond) + len(cond) - 1): return 1 if len(spring) == 0 or spring[0] != '#': return solve_r(spring[1:], cond)
if fulfills(spring, cond): return 1 else: return 0
sols = 0
not_dam = spring.count('?') + spring.count('#') - sum(cond)
if not_dam < 1: return 0 def hashtag(spring, cond):
inds = list(locate(spring, lambda x: x == '?')) c = cond[0]
for c in combinations(inds, not_dam): if len(spring) < c: return 0
rs = list(spring) for x in range(c):
for i in c: if spring[x] == '.': return 0
rs[i] = '.' return dot(spring[c:], cond[1:])
if fulfills(''.join(rs),cond): sols += 1
return sols
@memo @memo
def solve_r(spring, cond): def solve_r(spring, cond):
if cond == '': return 1 cond = [int(c) for c in cond]
cond = [int(c) for c in cond.split(',')] if cond == []: return 1 if spring.count('#') == 0 else 0
spring = spring.strip('.') if not '?' in spring: return 1 if fulfills(spring, cond) else 0
inds = list(locate(spring, lambda x: x == '.')) if spring == '': return 0
if inds == []: return dot(spring, cond) + hashtag(spring, cond)
if len(spring) > 10: print(spring, cond)
return solve_row1(spring, cond)
i = inds[0]
sols = 0
for j in range(0, len(cond)):
if sum(cond[:j]) <= len(list(locate(spring[:i], lambda x: x != '.'))) and sum(cond[j:]) <= len(list(locate(spring[i:], lambda x: x != '.'))):
cond1, cond2 = ','.join([str(c) for c in cond[:j]]), ','.join([str(c) for c in cond[j:]])
sols += solve_r(spring[:i], cond1) * solve_r(spring[i+1:], cond2)
return sols
if __name__ == '__main__': if __name__ == '__main__':
@ -57,9 +43,8 @@ if __name__ == '__main__':
res1 = 0 res1 = 0
res2 = 0 res2 = 0
for s in springs: for s in springs:
res1 += solve_r(*s) res1 += solve_r(s[0], [int(c) for c in s[1].split(',')])
res2 += solve_r('?'.join([s[0]]*5),','.join((s[1].split(','))*5)) res2 += solve_r('?'.join([s[0]]*5),[int(c) for c in s[1].split(',')*5])
print(solve_r('?'.join([s[0]]*5),','.join((s[1].split(','))*5)))
# challenge 1 # challenge 1
res1 = str(res1) res1 = str(res1)

Loading…
Cancel
Save