Advertisement
PotatoInBrackets

Aoc Day 7

Dec 8th, 2022
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. RawData := FileOpen(A_ScriptDir "\aoc7.txt", "r").Read(), RawData.Close()
  2. Data := StrSplit(RawData, "`n", "`r")
  3.  
  4. FileTree := {"/":{Child: [], files:[]}}
  5. for k, v in Data
  6. {
  7.     line := StrSplit(v, A_Space)
  8.     if (line[1] = "$")
  9.     {
  10.         if (line[2] = "cd")
  11.         {
  12.             Switch line[3]
  13.             {
  14.             Case "/":
  15.                 FullPath := "/"
  16.             Case "..":
  17.                 FullPath := SubStr(FullPath, 1, InStr(FullPath, "\", ,0)-1)
  18.             Default:
  19.                 FullPath := FullPath "\" line[3]
  20.             }
  21.         }
  22.     }
  23.     else if (line[1] = "dir")
  24.     {
  25.         FileTree[FullPath "\" line[2]] := {child: [], files: []}
  26.         FileTree[FullPath].child.push(FullPath "\" line[2])
  27.     }
  28.     else
  29.         FileTree[FullPath].files.push(line[1])
  30. }
  31.  
  32. ; part 1
  33. total := 0
  34. for k, dir in FileTree
  35.    total += (s := SubSum(dir)) > 100000 ? 0 : s
  36.  
  37.     msgbox % "part1: " total
  38.  
  39. ; part 2
  40. totalSize := 0
  41. for k, dir in FileTree
  42.     for i, size in dir.files
  43.         totalSize += size
  44.  
  45. absoluteSpace := 70000000, neededSpace := 30000000
  46. toFree := neededSpace - (absoluteSpace - totalSize)
  47. cDir := totalSize
  48.  
  49. for k, dir in FileTree
  50. {
  51.     size := SubSum(dir)
  52.     if ((size >= toFree) AND (size < cDir))
  53.         cDir := size
  54. }
  55. msgbox % "part2: " cDir
  56.  
  57. ; func
  58. ; returns sum of all .files size in folder + all child folders
  59. SubSum(obj)
  60. {
  61.     global FileTree
  62.     sum := 0
  63.     for k, size in obj.files
  64.         sum += size
  65.     if obj.child.count()
  66.         for k, child in obj.child
  67.             sum += SubSum(FileTree[child])
  68.     return sum
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement