From 33aeabd2f90d43b555df097ce17bd81e96b051b2 Mon Sep 17 00:00:00 2001 From: Quentin Selle <62110608+quentinselle@users.noreply.github.com> Date: Mon, 16 Dec 2024 01:16:54 +0100 Subject: [PATCH] Add day9 part2 - wip --- src/day9.rs | 87 +++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 81 insertions(+), 6 deletions(-) diff --git a/src/day9.rs b/src/day9.rs index 999eca2..7f42a88 100644 --- a/src/day9.rs +++ b/src/day9.rs @@ -97,17 +97,92 @@ pub fn part1(input: &[Disk]) -> usize { pos += 1; } } - _ => unreachable!(), + Disk::Free { blocks } => { + for _ in 0..blocks { + pos += 1; + } + } } } res } -// #[aoc(day9, part2)] -// pub fn part2(input: &[Disk]) -> usize { -// // dbg!(input); -// 0 -// } +#[aoc(day9, part2)] +pub fn part2(input: &[Disk]) -> usize { + let mut i = 0; + let mut input = input.to_vec(); + + loop { + // for j in &input { + // match j { + // Disk::File { id, blocks } => { + // print!("{}", id.to_string().repeat(*blocks)); + // } + // Disk::Free { blocks } => { + // print!("{}", ".".repeat(*blocks)); + // } + // } + // } + // println!(); + + match input[i] { + Disk::File { id: _, blocks: _ } => { + i += 1; + } + Disk::Free { + blocks: free_blocks, + } => { + if let Some(last) = input.pop() { + match last { + Disk::Free { blocks: _ } => continue, + Disk::File { id, blocks } => match blocks.cmp(&free_blocks) { + std::cmp::Ordering::Equal => { + input[i] = last; + i += 1; + } + std::cmp::Ordering::Less => { + input.insert(i, last); + input[i + 1] = Disk::Free { + blocks: free_blocks - blocks, + }; + i += 1; + } + std::cmp::Ordering::Greater => { + input[i] = Disk::File { + id, + blocks: free_blocks, + }; + input.push(Disk::File { + id, + blocks: blocks - free_blocks, + }); + i += 1; + } + }, + } + } + } + } + if i >= input.len() { + break; + } + } + + let mut res = 0; + let mut pos = 0; + for i in input { + match i { + Disk::File { id, blocks } => { + for _ in 0..blocks { + res += pos * id; + pos += 1; + } + } + _ => unreachable!(), + } + } + res +} #[cfg(test)] mod tests {