Improve lib and use it to solve 3 and 17.
This commit is contained in:
58
d3.py
58
d3.py
@@ -1,6 +1,6 @@
|
||||
import re
|
||||
from lib import *
|
||||
|
||||
NUMBERS = "0123456789"
|
||||
EXAMPLE = """
|
||||
467..114..
|
||||
...*......
|
||||
@@ -14,6 +14,42 @@ EXAMPLE = """
|
||||
.664.598..
|
||||
"""
|
||||
|
||||
def solve(i: Input, second=False):
|
||||
"""
|
||||
This is a new version I have implemented after the fact to test the
|
||||
improvements to my library. My original versions are `solve1` and `solve2`.
|
||||
"""
|
||||
g = i.grid2()
|
||||
if not second:
|
||||
parts = g.find_not(NUMBERS + ".")
|
||||
else:
|
||||
parts = g.find("*")
|
||||
|
||||
res = 0
|
||||
numbers = []
|
||||
for p in parts:
|
||||
numbers_gear = []
|
||||
for n in g.neighbors_adj(p):
|
||||
if g[n] in NUMBERS:
|
||||
while n in g and g[n] in NUMBERS:
|
||||
n = (n[0], n[1] - 1)
|
||||
number = ""
|
||||
n = (n[0], n[1] + 1)
|
||||
start = n
|
||||
while n in g and g[n] in NUMBERS:
|
||||
number += g[n]
|
||||
n = (n[0], n[1] + 1)
|
||||
numbers.append((int(number), n[0], start))
|
||||
numbers_gear.append(int(number))
|
||||
numbers_gear = list(set(numbers_gear))
|
||||
if len(numbers_gear) == 2:
|
||||
res += numbers_gear[0] * numbers_gear[1]
|
||||
|
||||
if second:
|
||||
return res
|
||||
else:
|
||||
return sum([n for n, _, _ in list(set(numbers))])
|
||||
|
||||
def clean(text: str) -> list[str]:
|
||||
return list(filter(lambda l: l.strip() != "", text.splitlines()))
|
||||
|
||||
@@ -29,7 +65,7 @@ def is_adj_to_symbol(x, y, lines):
|
||||
pass
|
||||
return False
|
||||
|
||||
def solve(lines: list[str]):
|
||||
def solve1(lines: list[str]):
|
||||
d = ""
|
||||
adj_to_symbol = False
|
||||
s = 0
|
||||
@@ -86,16 +122,18 @@ def solve2(lines: list[str]):
|
||||
return s
|
||||
|
||||
def main():
|
||||
example = clean(EXAMPLE)
|
||||
print("Example 1:", solve(example))
|
||||
data = clean(open("i3.txt").read())
|
||||
print("Solution 1:", solve(data))
|
||||
input = Input(EXAMPLE)
|
||||
print("Example 1:", solve(input))
|
||||
|
||||
example = clean(EXAMPLE)
|
||||
print("Example 2:", solve2(example))
|
||||
input = Input("i3.txt")
|
||||
print("Solution 1:", solve(input))
|
||||
|
||||
data = clean(open("i3.txt").read())
|
||||
print("Solution 2:", solve2(data))
|
||||
input = Input(EXAMPLE)
|
||||
print("Example 2:", solve(input, True))
|
||||
|
||||
input = Input("i3.txt")
|
||||
print("Solution 2:", solve(input, True))
|
||||
return
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
Reference in New Issue
Block a user