Skip to content

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

@pjfarleyiii

Description

@pjfarleyiii

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions