day 22 python part 1

main
magical 2022-12-21 21:35:46 -08:00
parent b7cfadf7b1
commit 6960c73439
4 changed files with 337 additions and 0 deletions

202
day22/input 100644

File diff suppressed because one or more lines are too long

14
day22/sample1.in 100644
View File

@ -0,0 +1,14 @@
...#
.#..
#...
....
...#.......#
........#...
..#....#....
..........#.
...#....
.....#..
.#......
......#.
10R5L5R10L4R5L5

12
day22/sample3.in 100644
View File

@ -0,0 +1,12 @@
>>v#
.#v.
#.v.
..v.
...#...v..v#
&gt;&gt;&gt;v...<em>&gt;</em>#.&gt;&gt;
..#v...#....
...&gt;&gt;&gt;&gt;v..#.
...#....
.....#..
.#......
......#.

109
day22/sol.py 100644
View File

@ -0,0 +1,109 @@
map = []
moves = ""
with open("input") as f:
for line in f:
if line == "\n":
break
map.append(line.rstrip("\n"))
moves = f.readline().strip()
F = {
0: (+1, 0),
1: (0, +1),
2: (-1, 0),
3: (0, -1),
}
#assert len(set(len(l) for l in map)) == 1
class Map:
def __init__(self, map):
self.map = map
self.starts = {}
for row in range(len(self.map)):
i = 0
while self.map[row][i] == ' ':
i += 1
self.starts[row] = i
self.row = 0
self.col = self.starts[0]
self.face = 0
def nextTile(self):
x,y = self.col, self.row
f = self.face
# 0 - E
# 1 - S
# 2 - W
# 3 - N
dx, dy = F[self.face]
if dx:
x += dx
if x < self.starts[y]:
x = len(self.map[y])-1
elif x >= len(self.map[y]):
x = self.starts[y]
if dy:
for _ in range(999):
y += dy
if y < 0:
y = len(self.map)-1
elif y >= len(self.map):
y = 0
if x > len(self.map[y]) or self.map[y][x] == ' ':
continue
break
assert self.map[y][x] != ' '
return x, y, self.map[y][x]
def turnLeft(self):
self.face = (self.face - 1) % 4
def turnRight(self):
self.face = (self.face + 1) % 4
def walk(self, n):
while n > 0:
x,y,c = self.nextTile()
if c == '#':
break
self.row = y
self.col = x
#self.map[y][x] = '>v<^'[self.face]
n -= 1
print(self.row, self.col)
def pos(self):
return self.row+1, self.col+1
def score(self):
r, c = self.pos()
return r*1000 + c *4 + self.face
print(moves)
m = Map(map)
i = 0
while i < len(moves):
if moves[i].isdigit():
j = i+1
while j < len(moves) and moves[j].isdigit():
j += 1
n = int(moves[i:j])
m.walk(n)
i = j
elif moves[i] == 'L':
m.turnLeft()
i += 1
elif moves[i] == 'R':
m.turnRight()
i += 1
else:
print("invalid move", moves[i], "at", i)
i += 1
print(m.row, m.col)
print(m.score())