Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "io/ioutil"
- "sort"
- "strconv"
- "strings"
- )
- type File struct {
- Name string
- Size int
- }
- type Directory struct {
- Name string
- Parent *Directory
- ChildDirs map[string]*Directory
- ChildFiles []File
- Size int
- }
- func main() {
- input, _ := ioutil.ReadFile("day_seven/input.txt")
- splitInput := strings.Split(strings.TrimSpace(string(input)), "\n")
- root := makeDirectory("root", nil)
- var command, arg string
- var currentDir *Directory
- for i := 0; i < len(splitInput); i++ {
- fmt.Sscanf(splitInput[i], "$ %s %s", &command, &arg)
- if command == "cd" {
- if arg == "/" {
- currentDir = root
- } else if arg == ".." {
- currentDir = currentDir.Parent
- } else {
- currentDir = currentDir.ChildDirs[arg]
- }
- } else if command == "ls" {
- j := i + 1
- for j < len(splitInput) && string(splitInput[j][0]) != "$" {
- s := strings.Split(splitInput[j], " ")
- part1, part2 := s[0], s[1]
- if part1 == "dir" {
- if _, ok := currentDir.ChildDirs[part2]; !ok {
- dir := makeDirectory(part2, currentDir)
- currentDir.ChildDirs[dir.Name] = dir
- }
- } else {
- size, _ := strconv.Atoi(part1)
- file := File{Name: part2, Size: size}
- currentDir.ChildFiles = append(currentDir.ChildFiles, file)
- }
- j++
- }
- i = j - 1
- }
- }
- hydrateDirectorySize(root)
- dirs := findDirectoriesOfAtMost(root, 100000)
- totalSize := 0
- for _, dir := range dirs {
- totalSize += dir.Size
- }
- println(totalSize)
- directorySizes := getDirectorySizes(root)
- sort.Ints(directorySizes)
- sizeNeeded := 30000000 - (70000000 - root.Size)
- var smallestPossible int
- for i, size := range directorySizes {
- _ = i
- if size >= sizeNeeded {
- smallestPossible = size
- break
- }
- }
- println(sizeNeeded)
- println(smallestPossible)
- }
- func hydrateDirectorySize(dir *Directory) {
- for _, file := range dir.ChildFiles {
- dir.Size += file.Size
- }
- for _, childDir := range dir.ChildDirs {
- hydrateDirectorySize(childDir)
- dir.Size += childDir.Size
- }
- }
- func findDirectoriesOfAtMost(dir *Directory, size int) []*Directory {
- var dirs []*Directory
- if dir.Size <= size {
- dirs = append(dirs, dir)
- }
- for _, childDir := range dir.ChildDirs {
- dirs = append(dirs, findDirectoriesOfAtMost(childDir, size)...)
- }
- return dirs
- }
- func getDirectorySizes(dir *Directory) []int {
- var sizes []int
- sizes = append(sizes, dir.Size)
- for _, dir := range dir.ChildDirs {
- sizes = append(sizes, getDirectorySizes(dir)...)
- }
- return sizes
- }
- func makeDirectory(name string, parentDir *Directory) *Directory {
- return &Directory{Name: name, Parent: parentDir, ChildDirs: map[string]*Directory{}}
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement