crlogic

Day7

Dec 7th, 2022
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. # Part 1
  2. [string[]]$historyLines ??= $puzzleInput -split '\n' | Select -SkipLast 1
  3. $structure = @{}
  4. $structure.'/' = [System.Collections.Generic.List[object]]::New()
  5. $pwd = '/'
  6. foreach ($line in $historyLines) {
  7. $cmd,$operation,$dirLine,$fileName,$fileSize = $null
  8. switch -Regex ($line) {
  9. '^\$\scd\s(?<operation>.*)$' {
  10. $operation = $matches.operation
  11. break
  12. }
  13. '^(\$\sls|dir\s.*)$' {
  14. break
  15. }
  16. '^(?<fileSize>\d+)\s(?<fileName>.+)$' {
  17. [string]$fileName = $matches.fileName
  18. [int]$fileSize = $matches.fileSize
  19. }
  20. default {
  21. #debugging..
  22. }
  23. }
  24.  
  25. # change directory
  26. switch -Regex ($operation) {
  27. $null {break}
  28. '\.\.' {
  29. $pwd,$null = $pwd -split '\w+/$'
  30. break
  31. }
  32. '/' {
  33. $pwd = '/'
  34. break
  35. }
  36. '\w*' {
  37. $pwd = $pwd,$_,'/' -join ''
  38. }
  39. }
  40. # ls
  41. if ($null -ne $fileName) {
  42. $fileData = [pscustomobject]@{
  43. Directory = $pwd
  44. FileName = $fileName
  45. FileSize = $fileSize
  46. }
  47. if ($null -eq $structure["$pwd"]) {
  48. $structure.$pwd = [System.Collections.Generic.List[object]]::New()
  49. }
  50. ($structure.$pwd).Add($fileData)
  51.  
  52. # Recursively add files to get lower folder sum
  53. if ($pwd -eq '/') {continue}
  54. $recursepwd = $pwd
  55. do {
  56. $recursepwd,$null = $recursepwd -split '\w+/$'
  57. if ($null -eq $structure["$recursepwd"]) {
  58. $structure.$recursepwd = [System.Collections.Generic.List[object]]::New()
  59. }
  60. ($structure.$recursepwd).Add($fileData)
  61. }
  62. until ($recursepwd -eq '/')
  63. }
  64. }
  65.  
  66. # do sums
  67. # Find all of the directories with a total size of at most 100000. What is the sum of the total sizes of those directories?
  68. $allPathSums = foreach ($key in $structure.keys) {
  69. ($structure.$key | Measure -Sum -Property fileSize).Sum
  70. }
  71. ($allPathSums | Where {$_ -le 100000} | Measure -Sum).Sum
  72.  
  73. # Part 2
  74. # you need unused space of at least 30000000. You need to find a directory you can delete that will free up enough space
  75. [int]$totalUsed = ($structure.'/'.filesize | Measure -Sum).Sum
  76. [int]$diffNeeded = 70000000 - $totalUsed
  77. [int]$mustDelete = 30000000 - $diffNeeded
  78. $allPathSums | Where {$_ -ge $mustDelete} | Sort | Select -First 1
Advertisement
Add Comment
Please, Sign In to add comment