-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path07.rs
97 lines (89 loc) · 2.41 KB
/
07.rs
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
#![feature(test)]
use rustc_hash::FxHashMap;
type Input<'a> = Vec<Node<'a>>;
struct Node<'a> {
size: u64,
parent_id: Option<usize>,
names: FxHashMap<&'a str, usize>,
visited: bool,
}
impl Node<'_> {
fn new(parent_id: Option<usize>) -> Self {
Self {
size: 0,
parent_id,
names: FxHashMap::default(),
visited: false,
}
}
}
fn setup(input: &str) -> Input {
let mut nodes = vec![Node::new(None)];
let mut pwd = 0;
let mut visiting = None;
for line in input.trim().lines() {
let mut split = line.split(' ');
match (split.next(), split.next(), split.next()) {
(Some("$"), Some("cd"), Some(dir)) => {
if dir == "/" {
pwd = 0;
} else if dir == ".." {
pwd = nodes[pwd].parent_id.unwrap_or(0)
} else {
pwd = match nodes[pwd].names.get(dir) {
Some(id) => *id,
None => {
let id = nodes.len();
nodes.push(Node::new(Some(pwd)));
nodes[pwd].names.insert(dir, id);
id
}
}
}
}
(Some(size), Some(_), None) => {
if let Ok(size) = size.parse::<u64>() {
if nodes[pwd].visited {
continue;
}
visiting = Some(pwd);
nodes[pwd].size += size;
}
}
_ => {
if let Some(v) = visiting {
nodes[v].visited = true;
visiting = None;
}
}
}
}
for i in (1..nodes.len()).rev() {
if let Node {
size,
parent_id: Some(parent_id),
..
} = nodes[i]
{
nodes[parent_id].size += size;
}
}
nodes
}
fn part1(nodes: &Input) -> u64 {
nodes
.iter()
.map(|node| node.size)
.filter(|x| *x <= 100000)
.sum()
}
fn part2(nodes: &Input) -> u64 {
let free = 70000000 - nodes[0].size;
nodes
.iter()
.map(|node| node.size)
.filter(|x| *x >= 30000000 - free)
.min()
.unwrap()
}
aoc::main!(2022, 7, ex: 1);