From 3e573bbdbfdcd35abae85305aeff66ae7e4774c8 Mon Sep 17 00:00:00 2001 From: Federico Igne Date: Wed, 8 Dec 2021 18:04:51 +0000 Subject: Day 7 --- day7/src/main.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 day7/src/main.rs (limited to 'day7/src/main.rs') diff --git a/day7/src/main.rs b/day7/src/main.rs new file mode 100644 index 0000000..8a44c07 --- /dev/null +++ b/day7/src/main.rs @@ -0,0 +1,28 @@ +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) }) +} -- cgit v1.2.3