day9, part1

This commit is contained in:
Joe Ardent 2025-01-03 11:18:34 -08:00
parent 75706b14e3
commit 01b077fc5f
4 changed files with 93 additions and 1 deletions

4
Cargo.lock generated
View file

@ -52,6 +52,10 @@ dependencies = [
"winnow",
]
[[package]]
name = "day09"
version = "0.1.0"
[[package]]
name = "memchr"
version = "2.7.4"

View file

@ -1,6 +1,6 @@
[workspace]
resolver = "2"
members = ["day01", "day02", "day03", "day04", "day05", "day06", "day07", "day08"]
members = ["day01", "day02", "day03", "day04", "day05", "day06", "day07", "day08", "day09"]
[workspace.dependencies]
winnow = "0.6"

6
day09/Cargo.toml Normal file
View file

@ -0,0 +1,6 @@
[package]
name = "day09"
version = "0.1.0"
edition = "2024"
[dependencies]

82
day09/src/main.rs Normal file
View file

@ -0,0 +1,82 @@
fn main() {
let input = std::fs::read_to_string("input").unwrap();
println!("{}", pt1(&input));
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Cell {
Free,
Block(usize),
}
fn pt1(input: &str) -> usize {
let mut next_id = 0;
let mut map = Vec::new();
let mut frees = Vec::new();
for (i, c) in input.chars().enumerate() {
let n = match c.to_digit(10) {
Some(n) => n as usize,
_ => {
continue;
}
};
if i % 2 == 0 {
let cell = Cell::Block(next_id);
for _ in 0..n {
map.push(cell);
}
next_id += 1;
} else {
for _ in 0..n {
frees.push(map.len());
map.push(Cell::Free);
}
}
}
let omap = map.clone();
let mut next_free = 0;
for (i, &b) in omap.iter().enumerate().rev() {
if b == Cell::Free {
continue;
}
let free = frees[next_free];
if i <= free {
break;
}
next_free += 1;
map.swap(free, i);
}
//println!("{map:?}");
map.iter()
.enumerate()
.map(|(i, &b)| match b {
Cell::Block(v) => i * v,
_ => 0,
})
.sum()
}
enum Block {
Free(usize),
// size, id
Block(usize, usize),
}
fn pt2(input: &str) -> usize {
todo!()
}
#[cfg(test)]
mod test {
use super::*;
static INPUT: &str = "2333133121414131402";
#[test]
fn p1() {
let v = pt1(INPUT);
assert_eq!(v, 1928);
}
}