Day 9 part 1 done
This commit is contained in:
parent
c595088352
commit
6f86208041
58
2024/rust/src/day9.rs
Normal file
58
2024/rust/src/day9.rs
Normal file
|
@ -0,0 +1,58 @@
|
|||
mod prelude;
|
||||
pub use crate::prelude::*;
|
||||
|
||||
fn main() {
|
||||
let input = day_input(9);
|
||||
show_answers(part1(&input), part2(&input));
|
||||
}
|
||||
|
||||
fn part1(input: &str) -> usize {
|
||||
let mut blocks: Vec<Option<usize>> = vec![];
|
||||
let mut free_blocks: usize = 0;
|
||||
for (i, len) in input.trim().bytes().map(|len| len - b'0').enumerate() {
|
||||
// every other iteration is "free space"
|
||||
let file_id = if i % 2 == 0 {
|
||||
Some((i / 2) as usize)
|
||||
} else {
|
||||
free_blocks += len as usize;
|
||||
None
|
||||
};
|
||||
for _ in 0..len {
|
||||
blocks.push(file_id);
|
||||
}
|
||||
}
|
||||
println!("{blocks:?}");
|
||||
let mut right = blocks.len() - 1;
|
||||
for left in 0..(right.clone() - free_blocks + 1) {
|
||||
if blocks[left].is_some() {
|
||||
continue;
|
||||
}
|
||||
while blocks[right].is_none() {
|
||||
right -= 1;
|
||||
}
|
||||
(blocks[left], blocks[right]) = (blocks[right], blocks[left]);
|
||||
}
|
||||
println!("{blocks:?}");
|
||||
|
||||
blocks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, b)| i * b.unwrap_or_default())
|
||||
.sum()
|
||||
}
|
||||
|
||||
fn part2(input: &str) -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test() {
|
||||
let input = r#"2333133121414131402"#;
|
||||
assert_eq!(part1(input), 1928);
|
||||
assert_eq!(part2(input), 1);
|
||||
}
|
||||
}
|
|
@ -2,8 +2,16 @@ mod prelude;
|
|||
pub use crate::prelude::*;
|
||||
|
||||
fn main() {
|
||||
let _input = day_input(0);
|
||||
show_answers(0, 0);
|
||||
let input = day_input(DAY);
|
||||
show_answers(part1(&input), part2(&input));
|
||||
}
|
||||
|
||||
fn part1(input: &str) -> i64 {
|
||||
0
|
||||
}
|
||||
|
||||
fn part2(input: &str) -> i64 {
|
||||
0
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
@ -11,5 +19,9 @@ mod tests {
|
|||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test() {}
|
||||
fn test() {
|
||||
let input = r#""#;
|
||||
assert_eq!(part1(input), 1);
|
||||
assert_eq!(part2(input), 0);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue