Skip to content

Instantly share code, notes, and snippets.

@markjenkins
Created December 7, 2016 05:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markjenkins/98364f39cd410d53dd5b13cac07f3133 to your computer and use it in GitHub Desktop.
Save markjenkins/98364f39cd410d53dd5b13cac07f3133 to your computer and use it in GitHub Desktop.
Functional solution to https://adventofcode.com/2016/day/1 part 1 with reduce() and lambda vs no lambda
#!/usr/bin/env python3
# Functional solution to https://adventofcode.com/2016/day/1 part 1
# with reduce() and lambda vs no lambda
# Mark Jenkins <mark@markjenkins.ca>
from functools import reduce
MOVEMENTS = ((0,1), (1,0), (0,-1), (-1,0))
DIRECTION_CHANGES = {"R": 1, "L": -1}
def next_pos(state, token):
displacement, direction = state
change_dir = DIRECTION_CHANGES[token[0]]
change_magnitude = int(token[1:])
new_direction = (direction + change_dir) % len(MOVEMENTS)
move = (change_magnitude*MOVEMENTS[new_direction][0],
change_magnitude*MOVEMENTS[new_direction][1] )
new_displacement = (displacement[0] + move[0], displacement[1] + move[1])
return new_displacement, new_direction
# commented out to avoid running twice
# displacement, direction = reduce(
# next_pos,
# input().split(", "),
# ((0, 0), 0)
# ) # reduce
# print( displacement )
# print( abs(displacement[0]) + abs(displacement[1]) )
# alternative way to write the above,
# some harder to read character code golf version with mandatory lambda
M = ((0,1), (1,0), (0,-1), (-1,0))
D = {"R": 1, "L": -1}
d, i = reduce(
lambda s,t: (
( s[0][0] + int(t[1:])*M[(s[1]+D[t[0]]) % len(M)][0],
s[0][1] + int(t[1:])*M[(s[1]+D[t[0]]) % len(M)][1],
),
(s[1]+D[t[0]]) % len(M)
),
input().split(", "),
((0, 0), 0)
)
# looks a little better in python 2 before PEP 3113 came along,
# but you can also take this as an argument against using lambda
# in the first place
# https://www.python.org/dev/peps/pep-3113/
# d, i = reduce(
# lambda (p,d),t: (
# ( p[0] + int(t[1:])*M[(d+D[t[0]]) % len(M)][0],
# p[1] + int(t[1:])*M[(d+D[t[0]]) % len(M)][1],
# ),
# (d+D[t[0]]) % len(M)
# ),
# raw_input().split(", "),
# ((0, 0), 0)
# )
#print(d)
print( abs(d[0]) + abs(d[1]) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment