-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathday07.nim
56 lines (44 loc) · 1.46 KB
/
day07.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
import re, tables, strutils, sets, math
const instructions = readFile("./inputs/07.txt").splitLines()
let pattern = re"\w+"
var
weights = initTable[string, int]()
children = initTable[string, seq[string]]()
allNodes = initHashSet[string]()
allKids = initHashSet[string]()
for line in instructions:
let
words = line.findAll(pattern)
name = words[0]
weight = words[1].parseInt()
kids = if len(words) > 2: words[2 .. ^1] else: @[]
weights[name] = weight
children[name] = kids
for node in children.keys():
allNodes.incl(node)
for kid in children[node]:
allKids.incl(kid)
var root = ""
for r in (allNodes - allKids): root = r
echo root
func findCorrectWeight(weights: seq[int]): int =
var counts = initCountTable[int]()
for weight in weights: counts.inc(weight)
return counts.largest.key
proc findOffspringsWeights(node: string): int =
var kidsWeights: seq[int] = @[]
for kid in children[node]:
kidsWeights.add(findOffspringsWeights(kid))
if len(kidsWeights.toHashSet) > 1:
let correct = findCorrectWeight(kidsWeights)
var wrong: int
for weight in kidsWeights.toHashSet:
if weight != correct: wrong = weight
let
difference = correct - wrong
wrongNode = children[node][kidsWeights.find(wrong)]
wrongWeight = weights[wrongNode]
echo wrongWeight + difference
return weights[node] + sum(kidsWeights) + difference
return weights[node] + sum(kidsWeights)
discard root.findOffspringsWeights()