Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[2016 Day 1 (Part 1 + 2)] [python] Alternate implementation #6

Open
pjfarleyiii opened this issue Nov 25, 2024 · 0 comments
Open

[2016 Day 1 (Part 1 + 2)] [python] Alternate implementation #6

pjfarleyiii opened this issue Nov 25, 2024 · 0 comments

Comments

@pjfarleyiii
Copy link

First of all, thank you very much for this substantial archive of AOC solutions.

I think a little differently, so while your unit-circle implementation of this day's puzzle made sense to me it, seemed a little complicated for such an easy challenge. This is my alternate solution to this day (both parts), which uses lists to store the directions and delta values and uses list.index() to find the element number to use in each list and sub-list.

import time


def main():
    with open("day1.txt", mode="rt") as f:
        direc = f.read().split(", ")
    print(f"Input has {len(direc)} directions")
    instrs = ["R", "L"]
    direcs = ["0", "+x", "+y", "-x", "-y"]
    xydelt = [[[1, 0], [0, -1], [1, 0], [0, 1], [-1, 0]],
             [[-1, 0], [0, 1], [-1, 0], [0, -1], [1, 0]]]
    xyhdng = [["+x", "-y", "+x", "+y", "-x"],
              ["-x", "+y", "-x", "-y", "+x"]]
    visited = [[0, 0]]
    got1st = False
    x, y, h = (0, 0, "0")
    for dx in range(len(direc)):
        d = direc[dx][0]
        xydir = instrs.index(d)
        hding = direcs.index(h)
        xynum = int(direc[dx][1:])
        dx, dy = xydelt[xydir][hding][0], xydelt[xydir][hding][1]
        for _ in range(xynum):
            x += dx
            y += dy
            if not [x, y] in visited:
                visited.append([x, y])
            elif not got1st:
                print(f"{x},{y} first to visit twice,dist={abs(x)+abs(y)}")
                got1st = True
        h = xyhdng[xydir][hding]
    print(f"Final x={x},y={y},dist={abs(x)+abs(y)},visited={len(visited)}")

if __name__ == "__main__":
    t1 = time.perf_counter()
    main()
    t2 = time.perf_counter()
    print(f"Execution time: {t2 - t1:0.4f} seconds")

Output from my solution with my inputs on an i7-6700K CPU @ 4.00GHz under Win10:

Input has 168 directions
148,-34 first to visit twice,dist=182
Final x=113,y=123,dist=236,visited=952
Execution time: 0.0074 seconds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant