advent-of-code

advent of code (partial solutions)
Log | Files | Refs | README

commit 05033fcc7ca02f6232df42cc774351505c714b39
parent 71d72375c0d602914e990741dfe657cff2fd9f0d
Author: alex wennerberg <alex@alexwennerberg.com>
Date:   Mon,  6 Dec 2021 21:27:46 -0800

Day 7

Diffstat:
A2021/aoc07.rs | 43+++++++++++++++++++++++++++++++++++++++++++
1 file changed, 43 insertions(+), 0 deletions(-)

diff --git a/2021/aoc07.rs b/2021/aoc07.rs @@ -0,0 +1,43 @@ +use std::collections::HashSet; +use std::error::Error; +use std::io::{self, Read}; + +fn main() -> Result<(), Box<dyn Error>> { + let mut state: [usize; 9] = [0; 9]; + let mut stdin = io::stdin(); + let mut input = String::new(); + stdin.read_to_string(&mut input); + let nums = input + .trim() + .split(",") + .map(|n| n.parse::<i32>().unwrap()) + .collect(); + let m = median(&nums).round() as i32; + let total: i32 = nums.iter().map(|n| (n - m).abs()).sum(); + println!("{}", total); + let total = |m2: i32| { + nums.iter() + .map(|n| { + let dif = (n - m2).abs(); + dif * (dif + 1) / 2 + }) + .sum() + }; + let part2: i32 = (0..1000).map(|n| total(n)).min().unwrap(); + println!("{}", part2); + Ok(()) +} + +// stolen +fn median(v: &Vec<i32>) -> f32 { + if v.len() < 1 { + return 0.0; + } + + let mut vec = v.clone(); + vec.sort(); + if vec.len() % 2 == 1 { + return *vec.get(vec.len() / 2).unwrap() as f32; + } + return (*vec.get(vec.len() / 2 - 1).unwrap() + *vec.get(vec.len() / 2).unwrap()) as f32 / 2.0; +}