Skip to content

Commit

Permalink
Do day 9 part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
samestep committed Dec 9, 2024
1 parent 80c5ace commit fa2e8f2
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
42 changes: 42 additions & 0 deletions src/day09/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,38 @@ pub fn puzzle1(input: &str) -> usize {
checksum(&blocks)
}

struct Span {
start: usize,
len: usize,
}

pub fn puzzle2(input: &str) -> usize {
let mut blocks = Vec::<Id>::new();
let files: Vec<Span> = (0..)
.zip(input.chars().array_chunks::<2>())
.map(|(id, [file, free])| {
let len = digit_usize(file).unwrap();
let start = blocks.len();
blocks.extend(repeat_n(id, len));
if let Some(len) = digit_usize(free) {
blocks.extend(repeat_n(-1, len));
}
Span { start, len }
})
.collect();
for (i, file) in files.into_iter().enumerate().rev() {
for start in 0..file.start {
let span = &mut blocks[start..start + file.len];
if span.iter().all(|&id| id < 0) {
span.fill(i as Id);
blocks[file.start..file.start + file.len].fill(-1);
break;
}
}
}
checksum(&blocks)
}

#[cfg(test)]
mod tests {
use super::*;
Expand All @@ -55,4 +87,14 @@ mod tests {
fn test_puzzle1_input() {
assert_eq!(puzzle1(INPUT), 6398608069280);
}

#[test]
fn test_puzzle2_example() {
assert_eq!(puzzle2(EXAMPLE), 2858);
}

#[test]
fn test_puzzle2_input() {
assert_eq!(puzzle2(INPUT), 6427437134372);
}
}
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ fn main() {
(8, 2) => day08::puzzle2(&input).to_string(),

(9, 1) => day09::puzzle1(&input).to_string(),
(9, 2) => day09::puzzle2(&input).to_string(),

_ => panic!("no puzzle {} for day {}", puzzle, day),
};
Expand Down

0 comments on commit fa2e8f2

Please sign in to comment.