-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday7.go
100 lines (86 loc) · 1.7 KB
/
day7.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package main
import (
"fmt"
"os"
"strconv"
"strings"
)
func check(e error) {
if e != nil {
panic(e)
}
}
type node struct {
size int
name string
parent *node
children []*node
}
func get_child_node(parent *node, folder string) *node {
for _, no := range parent.children {
if no.name == folder {
return no
}
}
return nil
}
func calculate_folder_sizes(this *node) int {
res := 0
if len(this.children) == 0 {
res = this.size
} else {
for _, no := range this.children {
res += calculate_folder_sizes(no)
}
this.size = res
}
return res
}
func main() {
input, err := os.ReadFile("./input/input7.txt")
check(err)
lines := strings.Split(string(input), "\r\n")
root := node{0, "/", nil, []*node{}}
dirs := []*node{&root}
current_dir := &root
for _, line := range lines {
if line[0] == '$' {
if line == "$ ls" {
// NOOP
} else if line[5] == '.' {
current_dir = current_dir.parent
} else {
current_dir = get_child_node(current_dir, strings.Split(line, " ")[2])
}
} else {
broken := strings.Split(line, " ")
size := 0
if broken[0] != "dir" {
size, _ = strconv.Atoi(broken[0])
}
new_node := node{size, broken[1], current_dir, []*node{}}
current_dir.children = append(current_dir.children, &new_node)
if broken[0] == "dir" {
dirs = append(dirs, &new_node)
}
}
}
calculate_folder_sizes(&root)
part1 := 0
for _, no := range dirs {
if no.size <= 100000 {
part1 += no.size
}
}
fmt.Println("Part 1: ", part1)
need_to_free := 30000000 - (70000000 - root.size)
min := 30000000
for _, no := range dirs {
if no.size >= need_to_free {
if no.size < min {
min = no.size
}
}
}
fmt.Println("Part 2: ", min)
}