summaryrefslogtreecommitdiff
path: root/day7/src/main.rs
diff options
context:
space:
mode:
authorFederico Igne <git@federicoigne.com>2021-12-08 18:04:51 +0000
committerFederico Igne <git@federicoigne.com>2021-12-08 18:04:51 +0000
commit3e573bbdbfdcd35abae85305aeff66ae7e4774c8 (patch)
tree1da7ab710de8ba79929d860d4564533611de5e09 /day7/src/main.rs
parent177c2419fa7c381311799cb8075d794c2298d78a (diff)
downloadaoc-3e573bbdbfdcd35abae85305aeff66ae7e4774c8.tar.gz
aoc-3e573bbdbfdcd35abae85305aeff66ae7e4774c8.zip
Day 7
Diffstat (limited to 'day7/src/main.rs')
-rw-r--r--day7/src/main.rs28
1 files changed, 28 insertions, 0 deletions
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 @@
1use std::fs;
2use std::path::Path;
3
4/* AOC21 Day 7: https://adventofcode.com/2021/day/7
5 *
6 * Some details about the solutions can be found here:
7 *
8 * https://web.archive.org/web/20211208180308/https://cdn.discordapp.com/attachments/541932275068174359/917882191298592788/crab_submarines.pdf
9 *
10 */
11fn main() {
12 let input = Path::new("resources").join("input.txt");
13 let content = fs::read_to_string(input).expect("Unable to read input file");
14 let mut report: Vec<i32> = content.split(",").map(|x| x.parse().expect("Malformed input")).collect();
15 report.sort();
16 println!("Ex1: The result is {}", ex1(&report));
17 println!("Ex1: The result is {}", ex2(&report));
18}
19
20fn ex1(report: &[i32]) -> i32 {
21 let median = report[(report.len() as f32 / 2.).round() as usize];
22 report.iter().fold(0, |a,x| a + (x-median).abs())
23}
24
25fn ex2(report: &[i32]) -> i32 {
26 let mean = (report.iter().sum::<i32>() as f32 / report.len() as f32).floor() as i32;
27 report.iter().fold(0, |a,x| { let d = (x-mean).abs(); a + (d*(d+1)/2) })
28}