aboutsummaryrefslogtreecommitdiff
path: root/2022/nim/day07
diff options
context:
space:
mode:
authorj-james2022-12-08 00:27:28 +0000
committerj-james2022-12-08 00:27:28 +0000
commit5186f8d891c60d61d406779d2890770f9e41f0e7 (patch)
tree35d467a614d037633c6d4cdf2ae837e186673b27 /2022/nim/day07
parent216616ab804a9b8df86511f356f692db5406d654 (diff)
Day Seven
Diffstat (limited to '2022/nim/day07')
-rw-r--r--2022/nim/day07/src/main.nim68
1 files changed, 68 insertions, 0 deletions
diff --git a/2022/nim/day07/src/main.nim b/2022/nim/day07/src/main.nim
new file mode 100644
index 0000000..da3bd90
--- /dev/null
+++ b/2022/nim/day07/src/main.nim
@@ -0,0 +1,68 @@
+# Day 7: No Space Left On Device
+import std/[os, strutils]
+
+let input = paramStr(1).readFile().strip().split("\n")
+
+type File = object
+ id: string
+ size: int
+
+type Dir = ref object
+ id: string
+ files: seq[File]
+ dirs: seq[Dir]
+ parent: Dir
+ size: int
+
+var root = Dir(id: "/")
+var current = root
+for line in input[1..^1]:
+ let output = line.split(" ")
+ if output.len == 2:
+ if output[0] == "$":
+ discard
+ elif output[0] == "dir":
+ current.dirs.add(Dir(id: output[1], parent: current))
+ else:
+ current.files.add(File(id: output[1], size: output[0].parseInt()))
+ else:
+ assert output[1] == "cd"
+ if output[2] == "..":
+ current = current.parent
+ else:
+ for i in current.dirs:
+ if i.id == output[2]:
+ current = i
+ break
+
+proc update_size(a: Dir) =
+ for i in a.files:
+ a.size += i.size
+ for i in a.dirs:
+ i.update_size()
+ a.size += i.size
+root.update_size()
+
+const maximum_size = 100000
+
+var sum = 0
+proc calc_size(a: Dir) =
+ if a.size <= maximum_size:
+ sum += a.size
+ for i in a.dirs:
+ i.calc_size()
+root.calc_size()
+echo sum
+
+const total_space = 70000000
+const update_space = 30000000
+let needed_space = update_space - (total_space - root.size)
+
+var min = update_space
+proc calc_min(a: Dir) =
+ if a.size >= needed_space:
+ min = min(a.size, min)
+ for i in a.dirs:
+ i.calc_min()
+root.calc_min()
+echo min