I dislike my solution even more than I dislike the problem, but meh, maybe some of the tricks are still news/useful for someone...
class SnakeGame(object): def __init__(self, width, height, food): food = [complex(*z) for z in food[::-1]] snake = collections.OrderedDict([(0, True)]) self.score = 0 def move(direction): head = next(reversed(snake)) + 1j ** 'DRU'.find(direction) if head in food[-1:]: food.pop() self.score += 1 else: snake.popitem(False) if head in snake or not (0 <= head.imag < width and 0 <= head.real < height): return -1 snake[head] = True return self.score self.move = move
@StefanPochmann Hi man, can you please explain the idea of using complex number here? I couldn't understand it. Thanks
@StefanPochmann Oh I think I got it, you use real number to represent row and complex number to represent column, so we could easily add 1 or 1j to row and col without doing something really ugly like pos + direction, pos + direction. Is it correct?
@zhongyuan9817 Yes, it makes computing the neighbor coordinate nicer. Even lets me compute what to add with
1j ** ... instead of hardcoding something like
[1, 1j, -1, -1j][...].
Just came up with an alternative initialization which I think is nicer. Not sure why I didn't do that earlier.
old: food = [x + y*1j for x, y in food[::-1]] new: food = [complex(*z) for z in food[::-1]]
@StefanPochmann This is indeed nicer, I particularly like
1j ** 'DRU'.find(direction)
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.