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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
|
use std::{collections::HashMap, str::FromStr, string::ParseError};
#[derive(Debug, Clone)]
struct File {
name: String,
size: usize,
}
#[derive(Debug, Clone)]
struct Directory {
name: String,
}
#[derive(Debug, Clone)]
enum FileType {
File(File),
Dir(Directory),
}
impl FromStr for File {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let splitted: Vec<_> = s.split(" ").collect();
let (size, name) = (
splitted[0].parse::<usize>().unwrap(),
splitted[1].to_string(),
);
Ok(File { name, size })
}
}
impl FromStr for Directory {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let splitted: Vec<_> = s.split(" ").collect();
let (_, name) = (splitted[0], splitted[1].to_string());
Ok(Directory { name })
}
}
impl FromStr for FileType {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if is_file(s) {
Ok(FileType::File(File::from_str(s).unwrap()))
} else {
Ok(FileType::Dir(Directory::from_str(s).unwrap()))
}
}
}
enum CommandType {
ChangeDir,
ListDir,
}
struct Command {
command_type: CommandType,
dir: Directory,
}
fn is_command(s: &str) -> bool {
s.contains("$ cd")
}
fn is_file(s: &str) -> bool {
s.split(" ").nth(0).unwrap().parse::<usize>().is_ok()
}
fn is_dir(s: &str) -> bool {
s.contains("dir")
}
fn calculate_size_part_one(
dir: String,
dirs: &HashMap<String, Vec<FileType>>,
list_of_dirs_under_100k: &mut Vec<usize>,
) -> usize {
let mut size: usize = 0;
let files = dirs.get(&dir).unwrap();
for file in files {
match file {
FileType::File(cur_file) => {
size += cur_file.size;
}
FileType::Dir(cur_dir) => {
let dir_sz =
calculate_size_part_one(cur_dir.name.clone(), dirs, list_of_dirs_under_100k);
if dir_sz <= 100000 {
list_of_dirs_under_100k.push(dir_sz)
}
size += dir_sz;
}
}
}
size
}
fn calculate_size_part_two(
dir: String,
dirs: &HashMap<String, Vec<FileType>>,
list_of_dirs: &mut Vec<usize>,
) -> usize {
let mut size: usize = 0;
let files = dirs.get(&dir).unwrap();
for file in files {
match file {
FileType::File(cur_file) => {
size += cur_file.size;
}
FileType::Dir(cur_dir) => {
let dir_sz = calculate_size_part_two(cur_dir.name.clone(), dirs, list_of_dirs);
list_of_dirs.push(dir_sz);
size += dir_sz;
}
}
}
size
}
impl FromStr for Command {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let splitted: Vec<_> = s.split(" ").collect();
let (_, cmd, dir) = (splitted[0], splitted[1], splitted[2]);
Ok(Command {
command_type: match cmd {
"cd" => CommandType::ChangeDir,
"ls" => CommandType::ListDir,
_ => unreachable!(),
},
dir: Directory {
name: dir.to_string(),
},
})
}
}
fn solve_part_one(data: &str) -> usize {
let mut dirs: HashMap<String, Vec<FileType>> = HashMap::new();
let mut cwd: String = "/".to_string();
for line in data.lines() {
if is_command(line) {
let cmd = Command::from_str(line).unwrap();
match cmd.command_type {
CommandType::ChangeDir => {
if cmd.dir.name == ".." && cwd != "/" {
let mut pos_of_last_backslash = cwd.len();
for i in (0..cwd.len() - 2).rev() {
if cwd.get(i..=i).unwrap() == "/" {
pos_of_last_backslash = i + 1;
break;
}
}
cwd = cwd[0..pos_of_last_backslash].to_string()
} else if cmd.dir.name != "/" {
cwd += format!("{}/", cmd.dir.name).as_str();
}
}
CommandType::ListDir => {}
}
}
if is_file(line) {
dirs.entry(cwd.clone())
.or_insert(vec![])
.push(FileType::File(File::from_str(line).unwrap()))
} else if is_dir(line) {
let dir_name = Directory::from_str(line).unwrap().name;
let cur_path = cwd.clone() + format!("{}/", dir_name).as_str();
dirs.entry(cwd.clone())
.or_insert(vec![])
.push(FileType::Dir(Directory { name: cur_path }))
}
}
let mut v: Vec<_> = vec![];
let _ = calculate_size_part_one("/".to_string(), &dirs, &mut v);
v.iter().sum()
}
fn solve_part_two(data: &str) -> usize {
let mut dirs: HashMap<String, Vec<FileType>> = HashMap::new();
let mut cwd: String = "/".to_string();
for line in data.lines() {
if is_command(line) {
let cmd = Command::from_str(line).unwrap();
match cmd.command_type {
CommandType::ChangeDir => {
if cmd.dir.name == ".." && cwd != "/" {
let mut pos_of_last_backslash = cwd.len();
for i in (0..cwd.len() - 2).rev() {
if cwd.get(i..=i).unwrap() == "/" {
pos_of_last_backslash = i + 1;
break;
}
}
cwd = cwd[0..pos_of_last_backslash].to_string()
} else if cmd.dir.name != "/" {
cwd += format!("{}/", cmd.dir.name).as_str();
}
}
CommandType::ListDir => {}
}
}
if is_file(line) {
dirs.entry(cwd.clone())
.or_insert(vec![])
.push(FileType::File(File::from_str(line).unwrap()))
} else if is_dir(line) {
let dir_name = Directory::from_str(line).unwrap().name;
let cur_path = cwd.clone() + format!("{}/", dir_name).as_str();
dirs.entry(cwd.clone())
.or_insert(vec![])
.push(FileType::Dir(Directory { name: cur_path }))
}
}
let mut v: Vec<_> = vec![];
let
|