aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorAn0nSaiko <porfeas12@gmail.com>2022-12-11 05:11:54 +0200
committerAn0nSaiko <porfeas12@gmail.com>2022-12-11 05:11:54 +0200
commit3ac84f5c00627e0594a88aa8890ce252de0e1d6c (patch)
tree141ea3ffd7fa482cdd9acd447812cbdf2d323f6c
parentTest commit (diff)
downloadaoc22-3ac84f5c00627e0594a88aa8890ce252de0e1d6c.tar.gz
aoc22-3ac84f5c00627e0594a88aa8890ce252de0e1d6c.zip
Day 9
-rw-r--r--day9/example.txt16
-rw-r--r--day9/solution.nim61
2 files changed, 69 insertions, 8 deletions
diff --git a/day9/example.txt b/day9/example.txt
index 9874df2..60bd43b 100644
--- a/day9/example.txt
+++ b/day9/example.txt
@@ -1,8 +1,8 @@
1R 4 1R 5
2U 4 2U 8
3L 3 3L 8
4D 1 4D 3
5R 4 5R 17
6D 1 6D 10
7L 5 7L 25
8R 2 8U 20
diff --git a/day9/solution.nim b/day9/solution.nim
index e69de29..ef25492 100644
--- a/day9/solution.nim
+++ b/day9/solution.nim
@@ -0,0 +1,61 @@
1import strutils
2import sequtils
3import sets
4
5type Move = tuple[Direction: char, Distance: int]
6type Position = tuple[r: int, c: int]
7
8proc parse(content: seq[string]): seq[Move] =
9 let moves = map(content,
10 proc (line: string): Move =
11 let temp = line.split(" ")
12 (temp[0][0], temp[1].parseInt())
13 )
14 return moves
15
16proc move(rope: var seq[Position], uniqPositions: var HashSet[Position]): void =
17 for i in 1 ..< rope.len():
18 # rope[i-1] = leader
19 # rope[i] = follower
20 let roffset = rope[i-1].r - rope[i].r
21 let coffset = rope[i-1].c - rope[i].c
22
23 if roffset in [2, -2]:
24 rope[i].r += int(roffset/2)
25 if coffset in [-1, 1]:
26 rope[i].c = rope[i-1].c
27
28 if coffset in [2, -2]:
29 rope[i].c += int(coffset/2)
30 if roffset in [-1, 1]:
31 rope[i].r = rope[i-1].r
32
33 uniqPositions.incl(rope[rope.len()-1])
34
35proc emulate(moves: seq[Move], len = 2): int =
36 var rope = newSeq[Position](len)
37 var uniqPositions: HashSet[Position]
38 init(uniqPositions)
39 echo rope
40 for move in moves:
41 for i in 1 .. move.Distance:
42 case move.Direction:
43 of 'U':
44 rope[0].r -= 1
45 of 'R':
46 rope[0].c += 1
47 of 'D':
48 rope[0].r += 1
49 of 'L':
50 rope[0].c -= 1
51 else:
52 assert(false)
53 move(rope, uniqPositions)
54
55 return len(uniqPositions)
56
57let content = readFile("./input.txt").strip().splitLines()
58let moves = parse(content)
59
60echo emulate(moves)
61echo emulate(moves, 10)