You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
87 lines
2.5 KiB
87 lines
2.5 KiB
#!/usr/bin/env python3
|
|
|
|
import sys
|
|
from copy import deepcopy
|
|
from termcolor import colored
|
|
|
|
|
|
def show(pipes, marked):
|
|
for y in range(len(pipes)):
|
|
for x in range(len(pipes[y])):
|
|
if marked[y][x] == 'x': print(colored(pipes[y][x], 'blue'), end = '')
|
|
elif marked[y][x] == 'I': print(colored(pipes[y][x], 'green'), end = '')
|
|
else: print(colored(pipes[y][x], 'grey'), end = '')
|
|
print('\n', end = '')
|
|
|
|
|
|
def count_vert(pipe, marked, x):
|
|
p = ''
|
|
t = 0
|
|
for i in range(x):
|
|
if marked[i] == 'x': p += pipe[i]
|
|
p = p.replace('-', '')
|
|
t += p.count('L7')
|
|
p = p.replace('L7', '')
|
|
t += p.count('FJ')
|
|
p = p.replace('FJ', '')
|
|
t += len(p)
|
|
return t
|
|
|
|
|
|
def next_step(pos, pipes):
|
|
y, x = pos
|
|
tile = pipes[y][x]
|
|
east = pipes[y][x+1] if x != len(pipes[y]) - 1 else 'x'
|
|
west = pipes[y][x-1] if x != 0 else 'x'
|
|
north = pipes[y-1][x] if y != 0 else 'x'
|
|
south = pipes[y+1][x] if y != len(pipes) - 1 else 'x'
|
|
if tile in ['-', 'L', 'F'] and east in ['-', '7', 'J']: return (y, x+1)
|
|
elif tile in ['|', '7', 'F'] and south in ['|', 'J', 'L']: return (y+1, x)
|
|
elif tile in ['|', 'J', 'L'] and north in ['|', '7', 'F']: return (y-1, x)
|
|
elif tile in ['-', '7', 'J'] and west in ['-', 'L', 'F']: return (y, x-1)
|
|
|
|
|
|
def measure_loop(start, p):
|
|
pipes = deepcopy(p)
|
|
position = next_step(start,pipes)
|
|
prev_position = position
|
|
position = next_step(position,pipes)
|
|
loop = 2
|
|
while position != start:
|
|
pipes[prev_position[0]][prev_position[1]] = 'x'
|
|
prev_position = position
|
|
position = next_step(position, pipes)
|
|
loop += 1
|
|
pipes[start[0]][start[1]] = 'x'
|
|
return loop, pipes
|
|
|
|
|
|
if __name__ == '__main__':
|
|
pipes = [list(line.strip('\n')) for line in open(sys.argv[1])]
|
|
start = (0,0)
|
|
for i,p in enumerate(pipes):
|
|
if 'S' in p:
|
|
start = (i, p.index('S'))
|
|
pipes[i][p.index('S')] = '-'
|
|
break
|
|
length, marked_loop = measure_loop(start, pipes)
|
|
|
|
# challenge 2
|
|
res2 = 0
|
|
for y in range(len(pipes)):
|
|
for x in range(len(pipes[y])):
|
|
if not marked_loop[y][x] == 'x':
|
|
c = count_vert(pipes[y], marked_loop[y], x)
|
|
if (c%2) == 1:
|
|
res2 += 1
|
|
marked_loop[y][x] = 'I'
|
|
|
|
show(pipes, marked_loop)
|
|
|
|
# challenge 1
|
|
res1 = str(int(length/2))
|
|
print(f"challenge 1:\n{res1}\n")
|
|
|
|
res2 = str(res2)
|
|
print(f"challenge 2:\n{res2}\n")
|
|
|
|
|