-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathday16.nim
68 lines (52 loc) · 1.47 KB
/
day16.nim
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
62
63
64
65
66
67
68
import strutils, sequtils, algorithm
const
instructions = readFile("./inputs/16.txt").split(',')
iterations = 1_000_000_000
programs = "abcdefghijklmnop"
type Parsed = object
first, pa, pb: char
second, xa, xb: int
func parse(instruction: string): Parsed =
let
first = instruction[0]
rest = instruction[1 .. instruction.high]
var x: seq[int]
case first
of 's':
result = Parsed(first: first, second: rest.parseInt)
of 'x':
x = rest.split('/').map(parseInt)
result = Parsed(first: first, xa: x[0], xb: x[1])
of 'p':
result = Parsed(first: first, pa: rest[0], pb: rest[^1])
else: discard
func cleanUp(instructions: seq[string]): seq[Parsed] =
for instruction in instructions:
result.add(parse(instruction))
let cleaned = instructions.cleanUp()
proc dance(dancers: string): string =
result = dancers
var a, b: int
for element in cleaned:
case element.first
of 's':
discard result.rotateLeft(-element.second)
of 'x':
swap(result[element.xa], result[element.xb])
of 'p':
a = result.find(element.pa)
b = result.find(element.pb)
result[a] = element.pb
result[b] = element.pa
else: discard
proc longDance(dancers: string): string =
var
dancers = dancers
seen = @[dancers]
for i in 1 .. iterations:
dancers = dancers.dance()
if dancers in seen:
return seen[iterations mod i]
seen.add(dancers)
echo programs.dance()
echo programs.longDance()