aboutsummaryrefslogtreecommitdiffstats
path: root/day9/solution.nim
blob: ef25492b999153f1653b918817c6bbecaa2ee487 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import strutils
import sequtils
import sets

type Move = tuple[Direction: char, Distance: int]
type Position = tuple[r: int, c: int]

proc parse(content: seq[string]): seq[Move] =
  let moves = map(content, 
                  proc (line: string): Move =
                    let temp = line.split(" ")
                    (temp[0][0], temp[1].parseInt())
              )
  return moves

proc move(rope: var seq[Position], uniqPositions: var HashSet[Position]): void =
  for i in 1 ..< rope.len():
    # rope[i-1] = leader
    # rope[i] = follower
    let roffset = rope[i-1].r - rope[i].r
    let coffset = rope[i-1].c - rope[i].c

    if roffset in [2, -2]:
      rope[i].r += int(roffset/2)
      if coffset in [-1, 1]:
        rope[i].c = rope[i-1].c

    if coffset in [2, -2]:
      rope[i].c += int(coffset/2)
      if roffset in [-1, 1]:
        rope[i].r = rope[i-1].r

  uniqPositions.incl(rope[rope.len()-1])

proc emulate(moves: seq[Move], len = 2): int =
  var rope = newSeq[Position](len)
  var uniqPositions: HashSet[Position]
  init(uniqPositions)
  echo rope
  for move in moves:
    for i in 1 .. move.Distance:
      case move.Direction:
        of 'U':
          rope[0].r -= 1
        of 'R':
          rope[0].c += 1
        of 'D':
          rope[0].r += 1
        of 'L':
          rope[0].c -= 1
        else:
          assert(false)
      move(rope, uniqPositions)

  return len(uniqPositions)

let content = readFile("./input.txt").strip().splitLines()
let moves = parse(content)

echo emulate(moves)
echo emulate(moves, 10)