From 874716448eab88c8fbd55dd9604945ab5c25425f Mon Sep 17 00:00:00 2001 From: Danila Fedorin Date: Thu, 8 Dec 2022 22:19:40 -0800 Subject: [PATCH] Add day 9 solutions --- day9.chpl | 39 ++++++++++++++++++++++++++++++++++++++ day9.cr | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 day9.chpl create mode 100644 day9.cr diff --git a/day9.chpl b/day9.chpl new file mode 100644 index 0000000..c184e10 --- /dev/null +++ b/day9.chpl @@ -0,0 +1,39 @@ +use IO, Set; + +const moveList = [ "L" => (-1, 0), "R" => (1, 0), "U" => (0, 1), "D" => (0, -1) ]; + +iter moves() { + for line in stdin.lines().strip() { + const (dir, _, n) = line.partition(" "); + yield (moveList[dir], n : int); + } +} + +config const length = 2; +var rope: [0.. 1 && dy == 0 { + tx += sgn(dx); + } else if abs(dy) > 1 && dx == 0 { + ty += sgn(dy); + } else if abs(dx) + abs(dy) > 2 { + tx += sgn(dx); + ty += sgn(dy); + } + return (tx, ty); +} + +var visited = new set((int, int)); + +for (delta, n) in moves() { + for 1..n { + rope[0] += delta; + for idx in 1.. {-1, 0}, "R" => {1, 0}, "U" => {0, 1}, "D" => {0, -1} } + +def move(h, d) + {h[0] + d[0], h[1] + d[1]} +end + +def follow(h, t) + hx, hy = h + tx, ty = t + dx = hx-tx + dy = hy-ty + + if dx.abs > 1 && dy.abs == 0 + tx += dx.sign + elsif dy.abs > 1 && dx.abs == 0 + ty += dy.sign + elsif dx.abs + dy.abs > 2 + tx += dx.sign + ty += dy.sign + end + + h = {hx, hy} + t = {tx, ty} + return {h, t} +end + +def simulate(knots, d) + knots[0] = move(knots[0], d) + (knots.size-1).times do |i| + knots[i], knots[i+1] = follow(knots[i], knots[i+1]) + end +end + + +knots = [{0, 0}] * 10 +INPUT.each do |cmd| + dir, n = cmd + d = diff[dir] + + n.times do + simulate(knots, d) + positions << knots.last + end +end + +puts positions.size