use std::fs; use std::path::Path; /* AOC21 Day 7: https://adventofcode.com/2021/day/7 * * Some details about the solutions can be found here: * * https://web.archive.org/web/20211208180308/https://cdn.discordapp.com/attachments/541932275068174359/917882191298592788/crab_submarines.pdf * */ fn main() { let input = Path::new("resources").join("input.txt"); let content = fs::read_to_string(input).expect("Unable to read input file"); let mut report: Vec = content.split(",").map(|x| x.parse().expect("Malformed input")).collect(); report.sort(); println!("Ex1: The result is {}", ex1(&report)); println!("Ex1: The result is {}", ex2(&report)); } fn ex1(report: &[i32]) -> i32 { let median = report[(report.len() as f32 / 2.).round() as usize]; report.iter().fold(0, |a,x| a + (x-median).abs()) } fn ex2(report: &[i32]) -> i32 { let mean = (report.iter().sum::() as f32 / report.len() as f32).floor() as i32; report.iter().fold(0, |a,x| { let d = (x-mean).abs(); a + (d*(d+1)/2) }) }