Avent of Code - Day 09 - Rope Bridge

in adventofcode •  2 years ago 

Advent of Code occurs at Dec 01 to 25 where each day, you will need to solve a puzzle. It is Festival and the problem statement is mostly related to Christmas.

Day 09 - Rope Bridge

https://adventofcode.com/2022/day/9

image.png

Q1

import sys

file1 = open(sys.argv[1], "r")

seen = set()

H = (0, 0)
T = (0, 0)
seen.add(tuple(T))
prevH = H

while True:
        line = file1.readline()
        if not line:
                break
        a, b = line.strip().split()
        for _ in range(int(b)):
                prevH = H
                if a == "R":
                        H = (H[0], H[1] + 1)
                elif a == "U":
                        H = (H[0] - 1, H[1])
                elif a == "L":
                        H = (H[0], H[1] - 1)
                elif a == "D":
                        H = (H[0] + 1, H[1])

                if abs(H[0] - T[0]) <= 1 and abs(H[1] - T[1]) <= 1:
                        continue
                T = prevH
                seen.add(tuple(T))

print(len(seen))

Q2

import sys
from collections import deque
from math import inf

file1 = open(sys.argv[1], "r")
seen = set()

snake = [(0, 0) for _ in range(10)]
seen.add(snake[0])

def get_near(A, B):
        rr, cc = A
        r, c = B
        def dis(r0, c0, r1, c1):
                return abs(r0 - r1) + abs(c0 - c1)
        D = inf
        for dr in range(-1, 2):
                for dc in range(-1, 2):
                        if dr != 0 or dc != 0:
                                d = dis(rr + dr, cc + dc, r, c)
                                if d < D:
                                        D = d
                                        ans = (rr + dr, cc + dc)
        return ans


while True:
        line = file1.readline()
        if not line:
                break
        a, b = line.strip().split()
        for _ in range(int(b)):
                x = snake[-1]
                if a == "R":
                        H = (x[0], x[1] + 1)
                elif a == "U":
                        H = (x[0] - 1, x[1])
                elif a == "L":
                        H = (x[0], x[1] - 1)
                elif a == "D":
                        H = (x[0] + 1, x[1])
                snake[-1] = H
                for i in range(8, -1, -1):
                        if (abs(snake[i][0] - snake[i + 1][0]) <= 1) and abs(snake[i][1] - snake[i + 1][1]) <= 1:
                                break
                        snake[i] = get_near(snake[i], snake[i + 1])
                seen.add(snake[0])

print(len(seen))

Q1 is basically a snake game. However, the Q2 is tricky - the body movement needs to be based on the rules, and not just follow its previous piece.


Steem to the Moon!

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE BLURT!