Last active
January 6, 2025 08:34
-
-
Save jhusain/c23da01c4d0de9b9d74c09db917d74f6 to your computer and use it in GitHub Desktop.
advent-of-code-9.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn defrag_disk(sectors: &mut [Option<u32>]) -> Option<()> { | |
let mut sectors = sectors; | |
loop { | |
// Find the first Empty sector | |
let left_idx = sectors.iter().position(|s| s.is_none())?; | |
// Find the last Full sector after the left_idx | |
let right_idx = sectors[left_idx + 1..].iter().rposition(|s| s.is_some())? + left_idx + 1; | |
// Swap the Empty and Full sectors | |
sectors.swap(left_idx, right_idx); | |
// Focus on the remaining unsorted range | |
sectors = &mut sectors[left_idx + 1..right_idx]; | |
} | |
} | |
fn main() { | |
let disk_map_str = "2333133121414131402"; | |
let disk_map: Vec<u32> = disk_map_str | |
.chars() | |
.map(|c| c.to_digit(10).unwrap()) | |
.collect(); | |
let disk_capacity: u32 = disk_map.iter().sum(); | |
let mut disk = Vec::with_capacity(disk_capacity.try_into().unwrap()); | |
let mut id = 0u32; | |
for (idx, num) in disk_map.into_iter().enumerate() { | |
let val = if idx % 2 == 0 { | |
let v = Some(id); | |
id += 1; | |
v | |
} else { | |
None | |
}; | |
for _ in 0..num { | |
disk.push(val); | |
} | |
} | |
defrag_disk(&mut disk); | |
println!("{:?}", disk); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment