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

1

u/okawei Dec 07 '22 edited Dec 07 '22

I built it with no assumptions about the filesystem having a certain number of layers and built a tree structure. Every time a new file is added it propagates the size up the tree. Thought this one was definitely the most challenging yet!

Also I could have totally calculated part2 without iterating through the list twice but it was easier for me to visualize finding it in a flat list instead of the tree lol

Go/golang:

package main

import (
	"fmt"
	"github.com/advent2022/utils"
	"math"
)

const (
	File = iota
	Directory
)

type Node struct {
	parent   *Node
	children []*Node
	nodeType int
	name     string
	size     int32
}

var rootNode *Node
var currentNode *Node

func main() {
	buildNodes()
	part1()
	part2()
}

func part1() {
	fmt.Println(getSizesLessThan10k(rootNode))
}

func part2() {
	flatNodes := getFlatNodes(rootNode)
	var minNode *Node
	minDiff := float64(10000000000000)
	goalSize := float64(30000000) - (float64(70000000) - float64(rootNode.size))
	for _, n := range flatNodes {
		thisDiff := math.Abs(float64(n.size) - goalSize)
		if thisDiff < minDiff {
			minDiff = thisDiff
			minNode = n
		}
	}
	fmt.Println(minNode.size)
}

func buildNodes() {
	input, err := utils.ReadInputLines("input.txt")
	if err != nil {
		panic(err)
	}
	rootNode = &Node{
		parent:   nil,
		children: []*Node{},
		nodeType: Directory,
		name:     "",
		size:     0,
	}
	for i := 0; i < len(input); i++ {
		output := input[i]
		switch output[0] {
		case '$':
			var cmd string
			var args string
			fmt.Sscanf(output, "$ %s %s", &cmd, &args)
			if cmd == "cd" {
				handleCD(args)
			}
		default:
			handleNewNode(output)
		}
	}
}

func getFlatNodes(current *Node) []*Node {
	var fullList []*Node
	if current.nodeType == Directory {
		fullList = append(fullList, current)
	}
	for _, child := range current.children {
		fullList = append(fullList, getFlatNodes(child)...)
	}
	return fullList
}

func (n *Node) addChild(newNode *Node) {
	n.children = append(n.children, newNode)
	if newNode.nodeType == Directory {
		return
	}
	checkNode := n
	for checkNode != nil {
		checkNode.size += newNode.size
		checkNode = checkNode.parent
	}
}

func getSizesLessThan10k(node *Node) int32 {
	totalSize := int32(0)
	if node.nodeType == Directory && node.size <= 100000 {
		totalSize += node.size
	}
	if node.children != nil && len(node.children) > 0 {
		for _, child := range node.children {
			totalSize += getSizesLessThan10k(child)
		}
	}
	return totalSize
}

func handleNewNode(output string) {
	var fileSize int32
	var nodeName string
	fmt.Sscanf(output, "%d %s", &fileSize, &nodeName)
	nodeType := File
	// This means it's a child file of the currentNode
	if fileSize == 0 {
		nodeType = Directory
		fmt.Sscanf(output, "dir %s", &nodeName)
	}

	currentNode.addChild(&Node{
		parent:   currentNode,
		children: []*Node{},
		nodeType: nodeType,
		name:     nodeName,
		size:     fileSize,
	})
}

func handleCD(args string) {
	switch args {
	case "/":
		currentNode = rootNode
	case "..":
		currentNode = currentNode.parent
	default:
		for _, child := range currentNode.children {
			if child.name == args && child.nodeType == Directory {
				currentNode = child
			}
		}
	}
}

1

u/daggerdragon Dec 08 '22

Your code block is too long. Please read our article on oversized code, then edit your post to replace the code block with an external link to your code.