Hey look, Day 15 is another one that took a super long time to calculate, though it was one of the easiest to code. It’s a fancy memory game, for Elves who apparently have computer brains. You start with a series of numbers, then the next number you say, is the difference between when the previous number was said, the last two times.

For example if you start saying this sequence, with 0,1,2,3 , the next number is 0, because 3 has only been said once, after that it’s 4, because 0 was said as the 5th number and the first number (5-1). After that it’s 0 again, because 4 has not been said before, then it’s 2, because 0 is at 7 and 5 (7-5), following that is 5, because 2 is at position 8 and 5 (8-5), and so on.

Both parts were the same problem, just with a different number of iterations, 2020 and 30,000,000. Calculating the 2020th number was quick, calculating the 30 millionth number, not so much.

Anyway, here is my code:


values = [0,8,15,2,12,1,4]

current = 0


while current < 30000000-7:
  check = values[-1]
  last = len(values) - values[::-1].index(check)
  if check in values[:last-1]:  
    temp=values[:last-1]
    temp.reverse()
    #print len(values)
    sec_last = len(values) - temp.index(check)-1
    next = last-sec_last
  else:
    next = 0
  values.append(next)
  #print next

  #print len(values)
  current+=1

print values[:-1]
print len(values)

I had some extra prints in there for the 2020, but printing everything for 30 million just slows it down. The final length print is just to verify that it’s giving me the correct iteration value. The main this this could use for clean up is to replace the while loop “-7” subtraction with subtracting a variable equal to the length of the initial values set, so that you could potentially feed it a value set that is larger or smaller.

The trickiest part here was figuring out the positions of the last two occurrences of a number, which meant counting backwards through the array of values. For the second number, I ended up using a reverse copy of the array, because I kept getting screwball answers trying to do it directly like I had for the first number. I would have liked to make it work with the more elegant solution but I didn’t have time to keep working on it.