Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- with open("2023_18input.txt", 'r') as file:
- my_input = file.read()
- get_way = {
- '1' : 'D',
- '3' : 'U',
- '0' : 'R',
- '2' : 'L',
- }
- raw_data = my_input
- raw_data = raw_data.split('\n')
- raw_data = [x.split(" ") for x in raw_data]
- plan = []
- for line in raw_data:
- plan.append((int(line[2].strip("()#")[:-1], 16), get_way[line[2].strip("()#")[-1]]))
- ways = {
- 'U' : (0, -1),
- 'D' : (0, 1),
- 'L' : (-1, 0),
- 'R' : (1, 0),
- }
- def add_pos(a, b):
- return tuple([x+y for x, y in zip(a, b)])
- max_h, max_v, min_h, min_v = 0, 0, 0, 0
- pos = (0, 0)
- inverse = {
- 'U' : 'D',
- 'D' : 'U',
- 'L' : 'R',
- 'R' : 'L',
- }
- for amount, way in plan:
- add_x, add_y = ways[way]
- x, y = pos
- pos = (x + (add_x * amount), y + (add_y * amount))
- if pos[0] > max_h:
- max_h = pos[0]
- if pos[0] < min_h:
- min_h = pos[0]
- if pos[1] > max_v:
- max_v = pos[1]
- if pos[1] < min_v:
- min_v = pos[1]
- h_correction, v_correction = 0, 0
- if min_h < 0:
- h_correction = -min_h
- if min_v < 0:
- v_correction = -min_v
- count = 0
- grid = {}
- multiples = {}
- # go through the instructions and record where all the vertices are
- # also count the number of squares on the border
- pos = (h_correction, v_correction)
- for i, (amount, way) in enumerate(plan):
- count += amount
- x, y = pos
- if y in grid:
- grid[y].append((x, way + inverse[plan[(i - 1) % len(plan)][1]]))
- else:
- grid[y] = [(x, way + inverse[plan[(i - 1) % len(plan)][1]])]
- add_x, add_y = ways[way]
- pos = add_pos((add_x*amount, add_y*amount), pos)
- # for blank rows, add one row and record how many times it needs to be counted
- rows = list(grid.keys())
- rows = sorted(rows)
- to_add = []
- for i, y in enumerate(rows[:-1]):
- if y+1 in rows:
- pass
- else:
- to_add.append(y+1)
- multiples[y+1] = rows[i+1] - (y+1)
- for entry in to_add:
- grid[entry] = []
- rows += to_add
- rows = sorted(rows)
- # fill in the vertical wall segments
- for i, y in enumerate(rows[1:], start=1):
- for place, vertex in grid[y]:
- if 'U' in vertex:
- y2 = rows[i - 1]
- while place not in [a for a, b in grid[y2]]:
- grid[y2].append((place, 'UD'))
- position = rows.index(y2)
- y2 = rows[position - 1]
- for y in grid:
- grid[y] = sorted(grid[y], key=lambda x: x[0])
- # go through row by row and count what's between the boundaries
- for y in range(1, max_v + v_correction):
- if y in grid:
- row_count = 0
- inside = False
- for i, (place, vertex) in enumerate(grid[y][:-1]):
- if 'U' in vertex:
- inside = not inside
- if 'R' not in vertex and inside:
- if y in multiples:
- multiple = multiples[y]
- else:
- multiple = 1
- row_count += grid[y][i+1][0] - place - 1
- print("%s in row %s, multiplied %s times" % (row_count, y, multiple))
- count += row_count * multiple
- print(count)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement