summaryrefslogtreecommitdiff
path: root/2022/day09.py
blob: 59bdf049991d03106be8bf280d2cfc0400575e89 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#!/usr/bin/env python3

# import numpy as np
from functools import reduce
from re import findall
from copy import deepcopy
import sys
import time

animate = False
# filename = "in/day09.ref"
# filename = "in/day09_2.ref"
filename = "in/day09.pzl"
data = open(filename).read()
lines = [line for line in data.rstrip('\n').split('\n')]


moves = []
for a in lines:
    m = [0, 0]
    direction, count = a.split(' ')
    if direction == 'R':
        m = [1, 0]
    elif direction == 'U':
        m = [0, 1]
    elif direction == 'D':
        m = [0, -1]
    elif direction == 'L':
        m = [-1, 0]

    # m = [int(count)*i for i in m]
    for _ in range(int(count)):
        moves.append(m)

# print(moves)

res1 = 0
h = [0,0]
t = [0,0]
visited = set()
visited.add(tuple(t))

for m in moves:
    h = [hi + mi for hi,mi in zip(h,m)]

    dx = h[0] - t[0]
    dy = h[1] - t[1]

    if abs(dx) > 1 or (abs(dx) > 0 and abs(dy) > 1):
        t[0] += dx//abs(dx)

    if abs(dy) > 1 or (abs(dy) > 0 and abs(dx) > 1):
        t[1] += dy//abs(dy)

    visited.add(tuple(t))


res2 = 0
ht = [[0,0] for i in range(10)]
visited9 = set()
visited9.add(tuple(ht[9]))


def print_grid(arr, c=''):
    lx = 100
    ly = 40
    grid = [['.' for _ in range(lx)] for _ in range(ly)]

    for i, (x, y) in enumerate(arr):
        try:
            grid[-y+ly//2][x+lx//2] = c if c!='' else str(i)
        except:
            pass

    grid[ly//2][lx//2] = "s"

    print('\x1b[2J')
    for line in grid:
        for c in line:
            print(c, end="")
        print("")
    time.sleep(1/20)

for m in moves:
    ht[0] = [hi + mi for hi,mi in zip(ht[0],m)]

    for i,_ in enumerate(ht):
        if i == 0:
            continue
        dx = ht[i-1][0] - ht[i][0]
        dy = ht[i-1][1] - ht[i][1]

        if abs(dx) > 1 or (abs(dx) > 0 and abs(dy) > 1):
            ht[i][0] += dx//abs(dx)

        if abs(dy) > 1 or (abs(dy) > 0 and abs(dx) > 1):
            ht[i][1] += dy//abs(dy)

    # print(ht)
    visited9.add(tuple(ht[9]))

    if animate:
        print_grid(ht)

# print(visited9)

res1 = len(visited)
res2 = len(visited9)

if animate == True:
    print_grid(visited9, c='#')
else:
    print('res1:', res1)
    print('res2:', res2)