diff --git a/2023/src/day15.rs b/2023/src/day15.rs index 7c1760f..dff9032 100644 --- a/2023/src/day15.rs +++ b/2023/src/day15.rs @@ -1,7 +1,46 @@ -pub fn part1(_input: &[u8]) -> anyhow::Result { - anyhow::bail!("Not implemented") +fn trim(input: &[u8]) -> &[u8] { + let whitespace = input + .iter() + .rev() + .take_while(|c| c.is_ascii_whitespace()) + .count(); + + &input[..(input.len() - whitespace)] +} + +fn hash(input: &[u8]) -> u32 { + input + .iter() + .fold(0, |cur, &c| ((cur + u32::from(c)) * 17) % 256) +} + +pub fn part1(input: &[u8]) -> anyhow::Result { + let input = trim(input); + + Ok(input + .split(|&c| c == b',') + .map(hash) + .sum::() + .to_string()) } pub fn part2(_input: &[u8]) -> anyhow::Result { anyhow::bail!("Not implemented") } + +#[cfg(test)] +mod tests { + use super::*; + + const SAMPLE: &[u8] = include_bytes!("samples/15.txt"); + + #[test] + fn sample_hash() { + assert_eq!(hash(b"HASH"), 52); + } + + #[test] + fn sample_part1() { + assert_eq!("1320", part1(SAMPLE).unwrap()); + } +} diff --git a/2023/src/samples/15.txt b/2023/src/samples/15.txt new file mode 100644 index 0000000..4f58f74 --- /dev/null +++ b/2023/src/samples/15.txt @@ -0,0 +1 @@ +rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7