2021: day07: part 1
This commit is contained in:
parent
56a5379a1b
commit
fa9827852d
5 changed files with 53 additions and 0 deletions
48
aoc2021/src/day07.rs
Normal file
48
aoc2021/src/day07.rs
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
use std::fmt::Write;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
const INPUT: &str = include_str!("../input/day07.txt");
|
||||
|
||||
pub fn run() -> Result<String> {
|
||||
let mut res = String::with_capacity(128);
|
||||
|
||||
writeln!(res, "part 1: {}", part1(INPUT)?)?;
|
||||
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
fn part1(input: &str) -> Result<u64> {
|
||||
let mut horizontal_positions = input
|
||||
.trim()
|
||||
.split(',')
|
||||
.map(|n| n.parse::<u64>().context("couldn't parse position"))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
|
||||
// TODO: try linear selection algorithm
|
||||
horizontal_positions.sort_unstable();
|
||||
let median = horizontal_positions[horizontal_positions.len() / 2];
|
||||
|
||||
Ok(horizontal_positions
|
||||
.iter()
|
||||
// TODO: use abs_diff when stabilized
|
||||
.map(|n| n.max(&median) - n.min(&median))
|
||||
.sum())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const PROVIDED: &str = include_str!("../input/day07_provided.txt");
|
||||
|
||||
#[test]
|
||||
fn part1_provided() {
|
||||
assert_eq!(part1(PROVIDED).unwrap(), 37);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part1_real() {
|
||||
assert_eq!(part1(INPUT).unwrap(), 340056);
|
||||
}
|
||||
}
|
||||
|
|
@ -6,3 +6,4 @@ pub mod day03;
|
|||
pub mod day04;
|
||||
pub mod day05;
|
||||
pub mod day06;
|
||||
pub mod day07;
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ use aoc2021::day03;
|
|||
use aoc2021::day04;
|
||||
use aoc2021::day05;
|
||||
use aoc2021::day06;
|
||||
use aoc2021::day07;
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let days: &[DayFunc] = &[
|
||||
|
|
@ -17,6 +18,7 @@ fn main() -> Result<()> {
|
|||
day04::run,
|
||||
day05::run,
|
||||
day06::run,
|
||||
day07::run,
|
||||
];
|
||||
|
||||
aoc::run(days)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue