From 64e22194d39d2914db1e3bf93c90de9e0791d9b3 Mon Sep 17 00:00:00 2001 From: Federico Igne Date: Fri, 1 Dec 2023 09:21:16 +0100 Subject: chore: reorganize project structure --- 2021/day07/src/main.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 2021/day07/src/main.rs (limited to '2021/day07/src/main.rs') diff --git a/2021/day07/src/main.rs b/2021/day07/src/main.rs new file mode 100644 index 0000000..8a44c07 --- /dev/null +++ b/2021/day07/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