day 10 remove unused fragments

This commit is contained in:
Peter 2020-12-10 16:38:15 +08:00
parent 27df3ee17a
commit 5e8fc1afb2

19
10/a.py
View File

@ -7,7 +7,7 @@ lines.add(0)
def a(transformers): def a(transformers):
v = 0 v = 0
dv = [3] #Always a 3 v transform at the end dv = [3] #Always a 3v transformer at the end
while v < max(transformers): while v < max(transformers):
v_ = min(set(range(v+1,v+4)).intersection(transformers)) v_ = min(set(range(v+1,v+4)).intersection(transformers))
dv.append(v_ - v) dv.append(v_ - v)
@ -17,10 +17,6 @@ def a(transformers):
count = dict(Counter(dv)) count = dict(Counter(dv))
return count[3]*count[1] return count[3]*count[1]
# print(lines)
# This is a recursive solution. IT works but it'll take an eternity to go through the whole list of transformers.
# Instead, we split
def b(c, v, transformers): def b(c, v, transformers):
for v_ in set(range(v+1,v+4)).intersection(lines): for v_ in set(range(v+1,v+4)).intersection(lines):
# print(v_) # print(v_)
@ -29,29 +25,20 @@ def b(c, v, transformers):
else: else:
c = b(c, v_, transformers) c = b(c, v_, transformers)
return c return c
# print(b(0, 0, lines)) #Does not work for big sets! # print(b(0, 0, lines)) #This is a recursive solution. IT works but it'll take an eternity to go through the whole list of transformers.
# print(b(0, 1, {1, 2, 3, 4})) #My solution: Split the set by 'gaps' (where there is only one path through to the next number), then multiply together
# print(b(0, 7, {7, 8, 9, 10, 11}))
def b_optimized(transformers): def b_optimized(transformers):
rel = { v: set(range(v+1,v+4)).intersection(transformers) for v in transformers } rel = { v: set(range(v+1,v+4)).intersection(transformers) for v in transformers }
rel.pop(max(transformers)) rel.pop(max(transformers))
# print(rel)
# print({ x if (vf in rel[x]) else None for x in rel }.intersection(transformers))
gaps = { list(rel[x])[0] if (len(rel[x]) == 1) else None for x in rel }.intersection(transformers) gaps = { list(rel[x])[0] if (len(rel[x]) == 1) else None for x in rel }.intersection(transformers)
gaps.add(list(rel)[0]) gaps.add(list(rel)[0])
gaps = sorted(gaps) gaps = sorted(gaps)
# print(gaps)
idx = 0 idx = 0
C = 1 C = 1
while idx+1 < len(gaps): while idx+1 < len(gaps):
s = sorted(set(range(gaps[idx],gaps[idx+1]+1)).intersection(transformers)) s = sorted(set(range(gaps[idx],gaps[idx+1]+1)).intersection(transformers))
# print(s)
if len(s) > 2: if len(s) > 2:
C *= b(0, list(s)[0], s) C *= b(0, list(s)[0], s)
# print(C, b(0, list(s)[0], s))
idx += 1 idx += 1
return C return C