# Python! import collections class grid: keys = { -2: { 0: '5'}, -1: {-1: 'A', 0: '6', 1: '2' }, 0: {-2: 'D', -1: 'B', 0: '7', 1: '3', 2: '1' }, 1: {-1: 'C', 0: '8', 1: '4' }, 2: { 0: '9'} } current_pos = [-2, 0] def move(self, direction): if direction in ['U', 'D']: pindex = 1 elif direction in ['L', 'R']: pindex = 0 if direction in ['U', 'R']: step = 1 elif direction in ['D', 'L']: step = -1 new_pos = [self.current_pos[0], self.current_pos[1]] new_pos[pindex] += step if abs(new_pos[0]) + abs(new_pos[1]) < 3: self.current_pos = new_pos def get_key(self): x = self.current_pos[0] y = self.current_pos[1] key = self.keys[x][y] return key g = grid() with open('02.txt') as file: lines = file.read().splitlines() code = '' for line in lines: for char in line: g.move(char) code += g.get_key() print(code)