-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday09.rs
More file actions
90 lines (75 loc) · 2.26 KB
/
Copy pathday09.rs
File metadata and controls
90 lines (75 loc) · 2.26 KB
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
//! Disk Fragmenter
//!
//! Summary:
use std::collections::HashMap;
use std::collections::VecDeque;
pub fn parse(input: &str) -> &str {
input.trim()
}
pub fn part1(input: &str) -> i64 {
solve_part1(input)
}
pub fn part2(input: &str) -> usize {
solve_part2(input)
}
fn solve_part1(input: &str) -> i64 {
let mut disc: VecDeque<i64> = VecDeque::new();
for (id, num) in input.chars().map(|v| v.to_digit(10).unwrap()).enumerate() {
if id % 2 == 0 {
for _ in 0..num {
disc.push_back((id / 2) as i64);
}
} else {
for _ in 0..num {
disc.push_back(-1_i64);
}
}
}
let mut disc_arranged: VecDeque<i64> = VecDeque::new();
while !disc.is_empty() {
let left = disc.pop_front().unwrap();
if left != -1 {
disc_arranged.push_back(left);
} else {
while !disc.is_empty() {
let right = disc.pop_back().unwrap();
if right != -1 {
disc_arranged.push_back(right);
break;
}
}
}
}
disc_arranged.iter().enumerate().map(|(id, v)| id as i64 * v).sum()
}
fn solve_part2(input: &str) -> usize {
let mut files: HashMap<usize, (usize, u32)> = HashMap::new();
let mut spaces: Vec<(usize, u32)> = Vec::new();
let mut pos = 0;
for (id, num) in input.chars().map(|v| v.to_digit(10).unwrap()).enumerate() {
if id % 2 == 0 {
files.insert(id / 2, (pos, num));
} else {
spaces.push((pos, num));
}
pos += num as usize;
}
for id in (0..files.len()).rev() {
let (pos, length) = files[&id];
for (id_space, (pos_space, length_space)) in spaces.clone().into_iter().enumerate() {
if pos < pos_space {
break;
}
if length <= length_space {
files.insert(id, (pos_space, length));
spaces[id_space] = (pos_space + length as usize, length_space - length);
break;
}
}
}
files
.keys()
.zip(files.values())
.map(|(id, (pos, len))| (*pos..*pos + *len as usize).map(|p| p * id).sum::<usize>())
.sum()
}