Advertisement
Guest User

Untitled

a guest
Dec 14th, 2020
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1. var input = []int64{15, 12, 0, 14, 3, 1}
  2.  
  3. func main() {
  4. sw := aoc.NewStopwatch()
  5. fmt.Println("Step 1:")
  6. fmt.Println(memoryGame(input, 2020))
  7. fmt.Println(sw.Elapsed())
  8.  
  9. sw.Reset()
  10. fmt.Println("Step 2:")
  11. fmt.Println(memoryGame(input, 30000000))
  12. fmt.Println(sw.Elapsed())
  13. }
  14.  
  15. // memoryGame simulates the memory game and returns the number stated on
  16. // the specified turn
  17. func memoryGame(input []int64, finalTurn int64) int64 {
  18. seen := make(map[int64]int64)
  19. for i, n := range input {
  20. seen[n] = int64(i + 1) // The first turn is turn 1, not turn 0
  21. }
  22. last := seen[int64(len(seen)-1)]
  23. wasNew := true
  24. delta := int64(0)
  25. for i := len(seen) + 1; int64(i) <= finalTurn; i++ {
  26. last = delta
  27. if wasNew {
  28. last = 0
  29. }
  30.  
  31. oldValue, found := seen[last]
  32. wasNew = !found
  33. if found {
  34. delta = int64(i) - oldValue
  35. }
  36. seen[last] = int64(i)
  37. }
  38. return last
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement