Last active
August 29, 2015 13:56
-
-
Save kylestev/9239910 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Cursor(object): | |
def __init__(self): | |
self.x, self.y = 0, 0 | |
self.dirs = { | |
'd': (0, 1), | |
'u': (0, -1), | |
'r': (1, 0), | |
'l': (-1, 0) | |
} | |
def consume_input(self, c): | |
if c in self.dirs: | |
x, y = self.dirs[c] | |
self.x += x | |
self.y += y | |
def get_at(self, selection): | |
if self.y >= len(selection) or self.x >= len(selection[0]): | |
return None | |
return selection[self.y][self.x] | |
def get_alphabet(): | |
alpha = [] | |
tmp = [] | |
for i in xrange(26): | |
if i % 5 == 0 and i > 0: | |
alpha.append(tmp) | |
tmp = [] | |
tmp.append(chr(ord('a') + i)) | |
alpha.append(tmp) | |
return alpha | |
def execute_moves(moves): | |
s = '' | |
alpha = get_alphabet() | |
c = Cursor() | |
for move in moves: | |
for m in move: | |
if m == '!': | |
s += c.get_at(alpha) | |
break | |
c.consume_input(m) | |
return s | |
def get_location(c, w): | |
return (ord(c) - ord('a')) % w, (ord(c) - ord('a')) / w | |
def get_moves_for_word(word): | |
d = [] | |
alpha = get_alphabet() | |
last = (0, 0) | |
for c in word: | |
x, y = get_location(c, 5) | |
dX, dY = x - last[0], y - last[1] | |
if dX == 0 and dY == 0: | |
d.append(['!']) | |
continue | |
d.append((['d' if dY > 0 else 'u'] * abs(dY)) + (['r' if dX > 0 else 'l'] * abs(dX)) + ['!']) | |
last = (x, y) | |
return d | |
def main(): | |
tests = ['google', 'kyle', 'hello', 'world', 'helloworld', 'programming'] | |
for test in tests: | |
print test, test == execute_moves(get_moves_for_word(test)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment