Unable to load image

Advent of Code 2022 : Day 9

grate filter edition

:#marseycapyhacker:

17
Jump in the discussion.

No email address required.

Another fun trick: use Python's complex numbers as coordinates:

    snek = [0j] * (10 if second else 2)
    visited = set([0j])

    def moveh(c, h):
        return h + {'U': 1j, 'R': 1, 'D': -1j, 'L': -1}[c]

    def movet(h, t):
        diff = h - t
        if abs(diff.real) > 1 and abs(diff.imag) > 1:
            return (t.real + diff.real / 2) + 1j * (t.imag + diff.imag / 2)
        elif abs(diff.real) > 1:
            return (t.real + diff.real / 2) + 1j * h.imag
        elif abs(diff.imag) > 1:
            return h.real                   + 1j * (t.imag + diff.imag / 2)
        return t

    for s in data:
        dir, dist = s.split()
        for _ in range(int(dist)):
            snek[0] = moveh(dir, snek[0])
            for i in range(len(snek) - 1):
                snek[i + 1] = movet(snek[i], snek[i + 1])
            visited.add(snek[-1])

    return len(visited)

edit: thx to @hbtz

    def movet(h, t):
        d = h - t
        if abs(d.real) > 1 or abs(d.imag) > 1:
            return t + d.real / max(1, abs(d.real)) + 1j * d.imag / max(1, abs(d.imag))
        return t
Jump in the discussion.

No email address required.

That is a fun trick i just used tuples. Will have to remember

Jump in the discussion.

No email address required.

I'm not sure how useful it was in this particular case, but getting vector addition for free is kinda fun! And unlike np vectors these puppies are hashable.

Jump in the discussion.

No email address required.

useful or not, using complex numbers as coordinates is the most intuitive thing ever. i wish i did it like that; it's a much nicer way to work with the problem

Jump in the discussion.

No email address required.

Complex numbers literally are coordinates in the complex plane.

Jump in the discussion.

No email address required.



Now playing: Donkey Kong Country Theme (DKC).mp3

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