AOC2022/day7/day7.go

92 lines
1.8 KiB
Go

package main
import (
"AOC2022/helper"
"fmt"
"os"
"strconv"
"strings"
)
type DirNode struct {
parent *DirNode
size int // Used to store data
children map[string]*DirNode
}
func main() {
args := os.Args[1:]
lines := helper.ReadTextFile(args[0])
defer helper.MeasureTime("Main")()
root := DirNode{nil, 0, map[string]*DirNode{}}
var currentNode *DirNode
currentNode = &root
for i := 1; i < len(lines); i++ {
line := lines[i]
if line[:1] != "$" {
splitLine := strings.Split(line, " ")
size := 0
if splitLine[0] != "dir" {
size = helper.RemoveError(strconv.Atoi(splitLine[0]))
}
newNode := DirNode{currentNode, size, map[string]*DirNode{}}
currentNode.children[splitLine[1]] = &newNode
} else if line[:4] == "$ ls" {
} else if line[:6] == "$ cd ." {
currentNode = currentNode.parent
} else if line[:4] == "$ cd" {
currentNode = currentNode.children[line[5:]]
}
}
getSize(&root)
dirs := getAllDir(&root)
part1(dirs)
part2(root.size, dirs)
}
func part2(usedSpace int, dirs []*DirNode) {
neededSpace := usedSpace - 40000000
toDeleteDir := &DirNode{nil, 70000000, map[string]*DirNode{}}
for _, dir := range dirs {
if dir.size >= neededSpace && dir.size < toDeleteDir.size {
toDeleteDir = dir
}
}
fmt.Println(toDeleteDir.size)
}
func part1(dirs []*DirNode) {
sum := 0
for _, dir := range dirs {
if dir.size < 100000 {
sum += dir.size
}
}
fmt.Println(sum)
}
func getAllDir(node *DirNode) []*DirNode {
dirs := []*DirNode{}
for _, child := range node.children {
if len(child.children) > 0 {
dirs = append(dirs, child)
dirs = append(dirs, getAllDir(child)...)
}
}
return dirs
}
func getSize(node *DirNode) {
size := 0
for _, child := range node.children {
if child.size == 0 {
getSize(child)
}
}
for _, child := range node.children {
size += child.size
}
node.size = size
}