AoC2021/src/day07.rs

65 lines
1.7 KiB
Rust
Raw Normal View History

2021-12-07 10:12:57 +01:00
use std::collections::HashMap;
use crate::Day;
2021-12-07 19:40:41 +01:00
use anyhow::Result;
2021-12-07 10:12:57 +01:00
pub struct Day07(HashMap<i32, i32>);
impl Day for Day07 {
2021-12-07 19:40:41 +01:00
fn init(content: String) -> Result<Self> {
2021-12-07 10:12:57 +01:00
let mut hm = HashMap::new();
2021-12-07 19:40:41 +01:00
for n in &content.split(',').map(str::parse).collect::<Result<Vec<_>, std::num::ParseIntError>>()? {
2021-12-07 10:12:57 +01:00
let entry = hm.entry(*n).or_insert(0);
*entry += 1;
}
2021-12-07 19:40:41 +01:00
Ok(Self(hm))
2021-12-07 10:12:57 +01:00
}
2021-12-07 19:40:41 +01:00
fn part1(&self) -> Result<String> {
2021-12-07 10:12:57 +01:00
let m = self.0.keys().copied().map(
|x| self.0.iter().map(
|(n, count)| (x - *n).abs() * (*count)
).sum::<i32>()
2021-12-07 19:40:41 +01:00
).min().ok_or_else(|| anyhow::Error::msg("Could not find min"))?;
2021-12-07 10:12:57 +01:00
2021-12-07 19:40:41 +01:00
Ok(format!("{}", m))
2021-12-07 10:12:57 +01:00
}
2021-12-07 19:40:41 +01:00
fn part2(&self) -> Result<String> {
let max = *self.0.keys().max().ok_or_else(|| anyhow::Error::msg("Could not find max"))?;
2021-12-07 10:12:57 +01:00
let m = (0..=max).map(
|x| self.0.iter().map(
|(n, count)| {
let n = (x - *n).abs();
(n * (n + 1) / 2) * (*count)
}
).sum::<i32>()
2021-12-07 19:40:41 +01:00
).min().ok_or_else(|| anyhow::Error::msg("Could not find min"))?;
Ok(format!("{}", m))
2021-12-07 10:12:57 +01:00
}
}
#[cfg(test)]
mod tests {
use crate::day07::Day07;
use crate::day::Day;
2021-12-07 19:40:41 +01:00
use anyhow::Result;
2021-12-16 20:23:05 +01:00
use crate::day_tests;
2021-12-07 10:12:57 +01:00
const INPUT: &str = "16,1,2,0,4,2,7,1,2,14";
#[test]
2021-12-07 19:40:41 +01:00
fn part1_test() -> Result<()> {
let d = Day07::init(INPUT.to_string())?;
assert_eq!("37", d.part1()?);
Ok(())
2021-12-07 10:12:57 +01:00
}
#[test]
2021-12-07 19:40:41 +01:00
fn part2_test() -> Result<()> {
let d = Day07::init(INPUT.to_string())?;
assert_eq!("168", d.part2()?);
Ok(())
2021-12-07 10:12:57 +01:00
}
2021-12-16 20:23:05 +01:00
day_tests!(Day07, "07", "357353", "104822130");
2021-12-07 10:12:57 +01:00
}