01020304050607080910111213141516171819202122232425

Advent of Code

2022/7

No Space Left On Device

in C#

by encse

You can hear birds chirping and raindrops hitting leaves as the expedition proceeds. Occasionally, you can even hear much louder sounds in the distance; how big do the animals get out here, anyway?

The device the Elves gave you has problems with more than just its communication system. You try to run a system update:

Read the full puzzle.

using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace AdventOfCode.Y2022.Day07;

[ProblemName("No Space Left On Device")]
class Solution : Solver {

    public object PartOne(string input) {
        return GetDirectorySizes(input).Where(size => size < 100000).Sum();
    }

    public object PartTwo(string input) {
        var directorySizes = GetDirectorySizes(input);
        var freeSpace = 70000000 - directorySizes.Max();
        return directorySizes.Where(size => size + freeSpace >= 30000000).Min();
    }

    private List<int> GetDirectorySizes(string input) {
        var path = new Stack<string>();
        var sizes = new Dictionary<string, int>();
        foreach (var line in input.Split("\n")) {
            if (line == "$ cd ..") {
                path.Pop();
            } else if (line.StartsWith("$ cd")) {
                path.Push(string.Join("", path)+line.Split(" ")[2]);
            } else if (Regex.Match(line, @"\d+").Success) {
                var size = int.Parse(line.Split(" ")[0]);
                foreach (var dir in path) {
                    sizes[dir] = sizes.GetValueOrDefault(dir) + size;
                }
            }
        }
        return sizes.Values.ToList();
    }
}

Please ☆ my repo if you like it!

© 2025 Advent of Code is a registered trademark in the US Images provided by Bing image creator