Unable to load image

Advent of Code 2022 : Day 9

grate filter edition

:#marseycapyhacker:

17
Jump in the discussion.

No email address required.

Part one wasn't too bad, but scaling for part 2 :marseysweating:. Probably easier than my inital impressions with a 20 seconds skim

Jump in the discussion.

No email address required.

Wasn't that bad (cleaned up a tad)

from collections import defaultdict

input_file = 'day_9_input'

with open(f'AdventOfCode2022/{input_file}.txt', 'r') as input:
    cmds = input.read().split('\n')

knots = {i: [0,0] for i in range(0, 2)}
positions = defaultdict(lambda: 1)
positions[(0, 0)]

dir_map = {
    'L': (0, -1),
    'R': (0, 1),
    'D': (1, -1),
    'U': (1, 1)
}

def move_knot(knot, knots=knots, positions=positions):
    if abs(knots[knot-1][0] - knots[knot][0]) > 1:
        if knots[knot-1][0] > knots[knot][0]:
            knots[knot][0] += 1
        else:
            knots[knot][0] += -1
        if abs(knots[knot-1][1] - knots[knot][1]) > 0:
            if knots[knot-1][1] > knots[knot][1]:
                knots[knot][1] += 1
            else:
                knots[knot][1] += -1
        if knot == len(knots)-1:
            positions[(knots[knot][0], knots[knot][1])]
    elif abs(knots[knot-1][1] - knots[knot][1]) > 1:
        if knots[knot-1][1] > knots[knot][1]:
            knots[knot][1] += 1
        else:
            knots[knot][1] += -1
        if abs(knots[knot-1][0] - knots[knot][0]) > 0:
            if knots[knot-1][0] > knots[knot][0]:
                knots[knot][0] += 1
            else:
                knots[knot][0] += -1
        if knot == len(knots)-1:
            positions[(knots[knot][0], knots[knot][1])]

def build_positions(cmds, knots, positions):
    for cmd in cmds:
        dir, dist = cmd.split(' ')
        dist = int(dist)
        unit_vector = dir_map[dir]

        for i in range(dist):
            knots[0][unit_vector[0]] += unit_vector[1]
            for j in range(1, len(knots)):
                move_knot(j, knots=knots, positions=positions)


build_positions(cmds, knots, positions)
print(sum([i for i in positions.values()]))

#Part 2: reset for 10 knots
knots = {i: [0,0] for i in range(0, 10)}
positions = defaultdict(lambda: 1)
positions[(0, 0)]

build_positions(cmds, knots, positions)

print(sum([i for i in positions.values()]))
Jump in the discussion.

No email address required.

what the frick

Jump in the discussion.

No email address required.

I cleaned it a little :marseycry:

Jump in the discussion.

No email address required.

:#marseywoah:

Jump in the discussion.

No email address required.

You would benefit from finding the conditions that handle + or - movement in the same statement and doing 4 checks instead of 8

Jump in the discussion.

No email address required.

Link copied to clipboard
Action successful!
Error, please refresh the page and try again.