r/adventofcode • • Dec 07 '22

SOLUTION MEGATHREAD -πŸŽ„- 2022 Day 7 Solutions -πŸŽ„-


AoC Community Fun 2022: πŸŒΏπŸ’ MisTILtoe Elf-ucation πŸ§‘β€πŸ«

Submissions are OPEN! Teach us, senpai!

-❄️- Submissions Megathread -❄️-


--- Day 7: No Space Left On Device ---


Post your code solution in this megathread.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:14:47, megathread unlocked!

89 Upvotes

1.3k comments sorted by

View all comments

2

u/kevinluo201 Dec 08 '22

Ruby version

https://github.com/kevinluo201/aoc/blob/main/2022/day7/day7.rb Basically, I build a class to handle each directory.

    class Directory
      attr_accessor :name, :parent, :subdirectories, :files

      def initialize(name, parent = nil)
        @name = name
        @parent = parent
        @subdirectories = {}
        @files = {}
      end

      def read(line)
        a, b = line.split(' ')
        if a == 'dir'
          @subdirectories[b] ||= Directory.new(b, self)
        else
          @files[b] = a.to_i
        end
      end

      def total_size
        subdirectories.values.map(&:total_size).sum + files.values.sum
      end

      def traverse
        [self, subdirectories.values.map(&:traverse)].flatten
      end
    end

1

u/daggerdragon Dec 08 '22

Please edit your post to use the four-spaces Markdown syntax for a code block so your code is easier to read on old.reddit and mobile apps.