Guest User

Untitled

a guest
Dec 7th, 2022
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. <?php
  2.  
  3. $inputFile = __DIR__.'/input.txt';
  4.  
  5. $lines = file($inputFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  6.  
  7. $currentPath = null;
  8. $files= [];
  9. $dirs = [];
  10. foreach ($lines as $line) {
  11. if (substr($line, 0, 1) === '$') {
  12. if (substr($line, 0, 5) === '$ cd ') {
  13. $cd = substr($line, 5);
  14. if ($cd === '/') {
  15. $currentPath = '/';
  16. } elseif ($cd === '..') {
  17. $currentPath = dirname($currentPath);
  18. if ($currentPath !== '/') {
  19. $currentPath .= '/';
  20. }
  21. } else {
  22. $currentPath .= $cd.'/';
  23. }
  24. }
  25. } else {
  26. list($type, $name) = explode(' ', $line);
  27. if ($type !== 'dir') {
  28. $files[$currentPath][$currentPath.$name] = $type;
  29. }
  30. }
  31. }
  32.  
  33. // Compute dir total sizes
  34. $dirSizes = [];
  35. foreach (array_keys($files) as $dir) {
  36. $dirSize = 0;
  37. foreach ($files as $dir2 => $dirFiles) {
  38. if (strpos($dir2, $dir) !== 0) {
  39. continue;
  40. }
  41. $dirSize += array_sum($dirFiles);
  42. }
  43. $dirSizes[$dir] = $dirSize;
  44. }
  45.  
  46. // Part 1
  47. $part1 = 0;
  48. foreach ($dirSizes as $dir => $size) {
  49. if ($size <= 100000) {
  50. $part1 += $size;
  51. }
  52. }
  53. var_dump($part1);
  54.  
  55.  
Advertisement
Add Comment
Please, Sign In to add comment