aoc-2022/day9/task1.nim

55 lines
922 B
Nim

import rdstdin
import strutils
import sets
type
Coords = tuple
x, y: int
proc diff(a, b: int): int =
if a > b: a - b
else: b - a
var line: string
var head, tail: Coords
var visited = newSeq[Coords](0)
while true:
let ok = readLineFromStdin("", line)
if not ok: break
let cmd = line.split(" ")
for i in 1 .. parseInt(cmd[1]):
case cmd[0]:
of "U": head.y.inc
of "D": head.y.dec
of "R": head.x.inc
of "L": head.x.dec
let x_diff = diff(head.x, tail.x)
let y_diff = diff(head.y, tail.y)
if x_diff + y_diff == 3:
# we are diagonal, yank
if x_diff == 2:
tail.y += head.y - tail.y
else:
tail.x += head.x - tail.x
if x_diff > 1:
if head.x > tail.x: tail.x.inc
else: tail.x.dec
if y_diff > 1:
if head.y > tail.y: tail.y.inc
else: tail.y.dec
visited.add(tail)
echo(visited.toHashSet.card)