Challenge 1.1


In [2]:
myinput = '/home/fmuinos/projects/adventofcode/2016/ferran/inputs/input1.txt'

Solution 1


In [3]:
def update_direction(face, turn):
    rotate = {'L': [-1,1], 'R': [1,-1]}
    new_face = (rotate[turn][0]*face[1], rotate[turn][1]*face[0])
    return new_face

def update_state(pos, face, turn, dist):
    new_face = update_direction(face, turn)
    new_pos = (pos[0] + dist * new_face[0], pos[1] + dist * new_face[1]) 
    return new_pos, new_face

def parse_list(path):
    with open(path, 'rt') as f: 
        mystr = f.read()
        mylist = mystr.rstrip('\n').split(', ')
        return mylist

In [4]:
def solver(path):
    hints = parse_list(path)
    pos = (0,0)
    face = (0,1)
    for hint in hints:
        turn = hint[0]
        dist = int(hint[1:])
        pos, face = update_state(pos, face, turn, dist)
    return abs(pos[0]) + abs(pos[1])

In [5]:
%%time
print(solver(myinput))


307
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 3.54 ms

Solution 2 (recursive)


In [6]:
def follow_hints(hints, pos, face):
    if len(hints) == 0:
        return abs(pos[0]) + abs(pos[1])
    else:
        hint = hints[0]
        turn = hint[0]
        dist = int(hint[1:])
        rotate = {'L': [-1,1], 'R': [1,-1]}
        new_face = (rotate[turn][0]*face[1], rotate[turn][1]*face[0])
        new_pos = (pos[0] + dist * new_face[0], pos[1] + dist * new_face[1])
        return follow_hints(hints[1:], new_pos, new_face)

In [7]:
%%time
hints = parse_list(myinput)
print(follow_hints(hints, [0,0], [0,1]))


307
CPU times: user 4 ms, sys: 0 ns, total: 4 ms
Wall time: 2.67 ms

Challenge 1.2


In [10]:
def first_repeated(path):
    hints = parse_list(path)
    pos = (0,0)
    face = (0,1)
    visited = set([])
    for hint in hints:
        turn = hint[0]
        dist = int(hint[1:])
        for i in range(dist):
            pos, new_face = update_state(pos, face, turn, 1)
            if not pos in visited:
                visited.add(pos)
            else:
                return abs(pos[0]) + abs(pos[1])
        face = new_face

In [11]:
first_repeated(myinput)


Out[11]:
165