My solutions to 2018's advent of code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

day12.nim 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import math, sequtils, strscans, strutils, tables
  2. type
  3. State = tuple[start: int, plants: string]
  4. const
  5. iterations = 50_000_000_000
  6. func score(state: State): int =
  7. for i, c in state.plants:
  8. if c == '#':
  9. result += i + state.start
  10. func iterate(state: State, rules: ref Table[string, char]): State =
  11. let
  12. input = "...." & state.plants & "...."
  13. start = state.start - 2
  14. var
  15. output = ""
  16. left = -1
  17. for i in 0..input.len - 5:
  18. let val = rules[input.substr(i, i + 4)]
  19. output &= val
  20. if left == -1 and val == '#':
  21. left = i - 1
  22. (start + left, output.substr(left).strip(leading=false, chars={'.'}))
  23. proc solve(initialState: State, rules: ref Table[string, char]) =
  24. var state = initialState
  25. for i in 1..iterations:
  26. var nextState = iterate(state, rules)
  27. if i == 20:
  28. echo nextState.score
  29. if state.plants == nextState.plants:
  30. # Same pattern of plants, they're just wandering off somewhere.
  31. let
  32. difference = nextState.score - state.score
  33. remaining = iterations - i
  34. score = nextState.score + difference * remaining
  35. echo score
  36. return
  37. state = nextState
  38. # If we reach here then the pattern didn't repeat, and it's
  39. # probably taken an *awfully* long time.
  40. echo state.score
  41. var
  42. rules = newTable[string, char]()
  43. lines = readFile("data/12.txt").strip.splitlines
  44. initialState: State = (0, lines[0].strip.substr(15))
  45. for line in lines[2..lines.len-1]:
  46. if line.strip.len > 0:
  47. rules.add(line.substr(0,4), line.substr(9)[0])
  48. solve(initialState, rules)