Compare commits
2 commits
f777d1a3b4
...
9159c4cc72
Author | SHA1 | Date | |
---|---|---|---|
dece | 9159c4cc72 | ||
dece | c88196ecae |
38
2021/day20.py
Normal file
38
2021/day20.py
Normal file
|
@ -0,0 +1,38 @@
|
|||
from operator import itemgetter as ig
|
||||
|
||||
with open("input20.txt") as f:
|
||||
lines = [line.rstrip() for line in f]
|
||||
iea = lines[0]
|
||||
data = {
|
||||
(x, y): c == "#"
|
||||
for x, line in enumerate(lines[2:])
|
||||
for y, c in enumerate(line)
|
||||
}
|
||||
|
||||
|
||||
def near(x, y):
|
||||
return ((a, b) for a in range(x - 1, x + 2) for b in range(y - 1, y + 2))
|
||||
|
||||
|
||||
def enhance(image, unkv):
|
||||
next_image = {}
|
||||
xmin, ymin = min(image, key=ig(0))[0] - 1, min(image, key=ig(1))[1] - 1
|
||||
xmax, ymax = max(image, key=ig(0))[0] + 1, max(image, key=ig(1))[1] + 1
|
||||
for x in range(xmin, xmax + 1):
|
||||
for y in range(ymin, ymax + 1):
|
||||
v = 0
|
||||
for nnp in near(x, y):
|
||||
v = (v << 1) | int(image.get(nnp, unkv))
|
||||
next_image[(x, y)] = iea[v] == "#"
|
||||
return next_image
|
||||
|
||||
|
||||
def solve(num_steps):
|
||||
image = data
|
||||
for i in range(num_steps):
|
||||
image = enhance(image, i % 2 == 1)
|
||||
print(sum(image.values()))
|
||||
|
||||
|
||||
solve(2)
|
||||
solve(50)
|
48
2021/day21.py
Normal file
48
2021/day21.py
Normal file
|
@ -0,0 +1,48 @@
|
|||
from functools import cache
|
||||
|
||||
with open("input21.txt") as f:
|
||||
lines = [line.rstrip() for line in f]
|
||||
ipos = (int(lines[0].rsplit()[-1]), int(lines[1].rsplit()[-1]))
|
||||
|
||||
pos = list(ipos)
|
||||
scores = [0, 0]
|
||||
num_rolls = 0
|
||||
turn = 0
|
||||
while scores[0] < 1000 and scores[1] < 1000:
|
||||
roll = sum(range(num_rolls + 1, num_rolls + 4))
|
||||
num_rolls += 3
|
||||
pos[turn] = pos[turn] + roll
|
||||
pos[turn] = pos[turn] - ((pos[turn] - 1) // 10) * 10
|
||||
scores[turn] += pos[turn]
|
||||
turn = (turn + 1) % 2
|
||||
print(min(scores) * num_rolls)
|
||||
|
||||
rolls_prob = [
|
||||
a + b + c for a in range(1, 4) for b in range(1, 4) for c in range(1, 4)
|
||||
]
|
||||
|
||||
|
||||
@cache
|
||||
def play(pos, scores, turn):
|
||||
if scores[0] >= 21:
|
||||
return 1, 0
|
||||
if scores[1] >= 21:
|
||||
return 0, 1
|
||||
|
||||
w1, w2 = 0, 0
|
||||
nturn = (turn + 1) % 2
|
||||
for r in rolls_prob:
|
||||
p = pos[turn] + r
|
||||
p = p - ((p - 1) // 10) * 10
|
||||
if turn == 0:
|
||||
npos = p, pos[1]
|
||||
nscores = scores[0] + p, scores[1]
|
||||
else:
|
||||
npos = pos[0], p
|
||||
nscores = scores[0], scores[1] + p
|
||||
res1, res2 = play(npos, nscores, nturn)
|
||||
w1, w2 = w1 + res1, w2 + res2
|
||||
return w1, w2
|
||||
|
||||
|
||||
print(max(play(ipos, (0, 0), 0)))
|
Loading…
Reference in a new issue