import tables iterator play(start: seq[int]): int = var spoke = initTable[int, int]() var turn = 0 var nextSpeak = 0 for i in start: turn += 1 spoke[i] = turn yield i nextSpeak = 0 while true: turn += 1 yield nextSpeak var lastSpoke = spoke.getOrDefault(nextSpeak, -1) spoke[nextSpeak] = turn if lastSpoke == -1: nextSpeak = 0 else: nextSpeak = turn - lastSpoke proc solve(s: seq[int], n: int): int = var i = 0 for x in play(s): inc i if i == n: echo x break echo solve(@[5,1,9,18,13,8,0], 30000000)