aoc2022/d9.py

129 lines
2.9 KiB
Python
Raw Normal View History

2023-12-07 03:12:59 +01:00
EXAMPLE = """
R 4
U 4
L 3
D 1
R 4
D 1
L 5
R 2
"""
def clean(text: str) -> list[str]:
return list(filter(lambda l: l.strip() != "", text.splitlines()))
def new_pos(h_pos, t_pos, dir):
if dir == "R":
new_h_pos = (h_pos[0] + 1, h_pos[1])
elif dir == "U":
new_h_pos = (h_pos[0], h_pos[1] + 1)
elif dir == "L":
new_h_pos = (h_pos[0] - 1, h_pos[1])
elif dir == "D":
new_h_pos = (h_pos[0], h_pos[1] - 1)
elif dir == "NONE":
new_h_pos = (h_pos[0], h_pos[1])
else:
raise Exception("Unexpected direction.")
# xxxxx
# x---x
# x-O-x
# x---x
# xxxxx
dx, dy = t_pos[0] - new_h_pos[0], t_pos[1] - new_h_pos[1]
delta = {
(-1, -1): (0, 0),
(-1, 0): (0, 0),
(-1, 1): (0, 0),
(0, -1): (0, 0),
(0, 0): (0, 0),
(0, 1): (0, 0),
(1, -1): (0, 0),
(1, 0): (0, 0),
(1, 1): (0, 0),
(-2, 2): (1, -1),
(-2, 1): (1, -1),
(-2, 0): (1, 0),
(-2, -1): (1, 1),
(-2, -2): (1, 1),
(2, 2): (-1, -1),
(2, 1): (-1, -1),
(2, 0): (-1, 0),
(2, -1): (-1, 1),
(2, -2): (-1, 1),
(-1, 2): (1, -1),
(-1, -2): (1, 1),
(0, 2): (0, -1),
(0, -2): (0, 1),
(1, 2): (-1, -1),
(1, -2): (-1, 1),
}
dx_, dy_ = delta[(dx, dy)]
new_t_pos = t_pos[0] + dx_, t_pos[1] + dy_
# print(f"{h_pos=} {t_pos=} {dir=}")
# print(f"{new_h_pos=} {dx=} {dy=}")
# print(f"{new_t_pos=}")
# print("----")
return new_t_pos, new_h_pos
def solve(lines: list[str]):
pos = set()
h_pos = (0, 0)
t_pos = (0, 0)
pos.add(t_pos)
for i in range(len(lines)):
dir, amount = lines[i].split()
for _ in range(int(amount)):
t_pos, h_pos = new_pos(h_pos, t_pos, dir)
pos.add(t_pos)
# 44:00
return len(pos)
EXAMPLE2 = """
R 5
U 8
L 8
D 3
R 17
D 10
L 25
U 20
"""
def solve2(lines: list[str]):
vis = set()
poss = [(0, 0) for _ in range(10)]
vis.add((0, 0))
for i in range(len(lines)):
dir, amount = lines[i].split()
for _ in range(int(amount)):
for i in range(len(poss) - 1):
h_pos = poss[i]
t_pos = poss[i + 1]
if i == 0:
t_pos, h_pos = new_pos(h_pos, t_pos, dir)
else:
t_pos, h_pos = new_pos(h_pos, t_pos, "NONE")
poss[i] = h_pos
poss[i + 1] = t_pos
vis.add(poss[-1])
# 58:00
return len(vis)
def main():
example = clean(EXAMPLE)
print("Example 1:", solve(example))
data = clean(open("i9.txt").read())
print("Solution 1:", solve(data))
example = clean(EXAMPLE2)
print("Example 2:", solve2(example))
data = clean(open("i9.txt").read())
print("Solution 2:", solve2(data))
if __name__ == "__main__":
main()