Skip to content

Commit

Permalink
Add day9 part2 - wip
Browse files Browse the repository at this point in the history
  • Loading branch information
qselle committed Dec 16, 2024
1 parent 7df8d44 commit 33aeabd
Showing 1 changed file with 81 additions and 6 deletions.
87 changes: 81 additions & 6 deletions src/day9.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 33aeabd

Please sign in to comment.