Skip to content

Commit 33aeabd

Browse files
committed
Add day9 part2 - wip
1 parent 7df8d44 commit 33aeabd

File tree

1 file changed

+81
-6
lines changed

1 file changed

+81
-6
lines changed

src/day9.rs

Lines changed: 81 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -97,17 +97,92 @@ pub fn part1(input: &[Disk]) -> usize {
9797
pos += 1;
9898
}
9999
}
100-
_ => unreachable!(),
100+
Disk::Free { blocks } => {
101+
for _ in 0..blocks {
102+
pos += 1;
103+
}
104+
}
101105
}
102106
}
103107
res
104108
}
105109

106-
// #[aoc(day9, part2)]
107-
// pub fn part2(input: &[Disk]) -> usize {
108-
// // dbg!(input);
109-
// 0
110-
// }
110+
#[aoc(day9, part2)]
111+
pub fn part2(input: &[Disk]) -> usize {
112+
let mut i = 0;
113+
let mut input = input.to_vec();
114+
115+
loop {
116+
// for j in &input {
117+
// match j {
118+
// Disk::File { id, blocks } => {
119+
// print!("{}", id.to_string().repeat(*blocks));
120+
// }
121+
// Disk::Free { blocks } => {
122+
// print!("{}", ".".repeat(*blocks));
123+
// }
124+
// }
125+
// }
126+
// println!();
127+
128+
match input[i] {
129+
Disk::File { id: _, blocks: _ } => {
130+
i += 1;
131+
}
132+
Disk::Free {
133+
blocks: free_blocks,
134+
} => {
135+
if let Some(last) = input.pop() {
136+
match last {
137+
Disk::Free { blocks: _ } => continue,
138+
Disk::File { id, blocks } => match blocks.cmp(&free_blocks) {
139+
std::cmp::Ordering::Equal => {
140+
input[i] = last;
141+
i += 1;
142+
}
143+
std::cmp::Ordering::Less => {
144+
input.insert(i, last);
145+
input[i + 1] = Disk::Free {
146+
blocks: free_blocks - blocks,
147+
};
148+
i += 1;
149+
}
150+
std::cmp::Ordering::Greater => {
151+
input[i] = Disk::File {
152+
id,
153+
blocks: free_blocks,
154+
};
155+
input.push(Disk::File {
156+
id,
157+
blocks: blocks - free_blocks,
158+
});
159+
i += 1;
160+
}
161+
},
162+
}
163+
}
164+
}
165+
}
166+
if i >= input.len() {
167+
break;
168+
}
169+
}
170+
171+
let mut res = 0;
172+
let mut pos = 0;
173+
for i in input {
174+
match i {
175+
Disk::File { id, blocks } => {
176+
for _ in 0..blocks {
177+
res += pos * id;
178+
pos += 1;
179+
}
180+
}
181+
_ => unreachable!(),
182+
}
183+
}
184+
res
185+
}
111186

112187
#[cfg(test)]
113188
mod tests {

0 commit comments

Comments
 (0)