Skip to content

Commit 82a0141

Browse files
committed
2022 day 7
1 parent 49c93ba commit 82a0141

File tree

3 files changed

+1179
-0
lines changed

3 files changed

+1179
-0
lines changed

2022/go/day7/day7.go

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"os"
6+
"strings"
7+
)
8+
9+
func main() {
10+
input, _ := os.ReadFile("../../input/day7.txt")
11+
root := parseTerminal(string(input))
12+
var part1 int
13+
root.forEach(func(n *node) {
14+
if n.fileSize == 0 && n.size() <= 100000 {
15+
part1 += n.size()
16+
}
17+
})
18+
fmt.Printf("part1: %v\n", part1)
19+
20+
needed := 30000000 - (70000000 - root.size())
21+
22+
smallest := 70000000
23+
root.forEach(func(n *node) {
24+
if n.size() >= needed && n.size() < smallest {
25+
smallest = n.size()
26+
}
27+
})
28+
fmt.Printf("part2: %v\n", smallest)
29+
}
30+
31+
type node struct {
32+
fileSize int
33+
parent *node
34+
nodes map[string]*node
35+
}
36+
37+
func parseTerminal(input string) *node {
38+
root := newNode(0, nil)
39+
cwd := root
40+
lines := strings.Split(input, "\n")
41+
for _, line := range lines {
42+
cwd = cwd.apply(line)
43+
}
44+
return root
45+
}
46+
47+
func (n *node) apply(line string) *node {
48+
name, size := "", 0
49+
if strings.HasPrefix(line, "$ cd ") {
50+
return n.cd(line[5:])
51+
} else if _, err := fmt.Sscanf(line, "%d %s", &size, &name); err == nil {
52+
return n.add(name, size)
53+
}
54+
return n
55+
}
56+
57+
func (n *node) cd(name string) *node {
58+
if name == "/" && n.parent == nil {
59+
return n
60+
} else if name == "/" {
61+
return n.cd("/")
62+
} else if name == ".." {
63+
return n.parent
64+
}
65+
if _, ok := n.nodes[name]; !ok {
66+
n.nodes[name] = newNode(0, n)
67+
}
68+
return n.nodes[name]
69+
}
70+
71+
func (n *node) add(name string, size int) *node {
72+
n.nodes[name] = newNode(size, n)
73+
return n
74+
}
75+
76+
func (n *node) size() int {
77+
if n.fileSize > 0 {
78+
return n.fileSize
79+
}
80+
var sum int
81+
for _, c := range n.nodes {
82+
sum += c.size()
83+
}
84+
return sum
85+
}
86+
87+
func newNode(size int, parent *node) *node {
88+
return &node{fileSize: size, parent: parent, nodes: make(map[string]*node)}
89+
}
90+
91+
func (n *node) forEach(f func(*node)) {
92+
for _, c := range n.nodes {
93+
f(c)
94+
c.forEach(f)
95+
}
96+
}

0 commit comments

Comments
 (0)