summaryrefslogtreecommitdiff
path: root/2021/day07/src/main.rs
diff options
context:
space:
mode:
authorFederico Igne <undyamon@disroot.org>2023-12-01 09:21:16 +0100
committerFederico Igne <undyamon@disroot.org>2023-12-01 09:21:16 +0100
commit64e22194d39d2914db1e3bf93c90de9e0791d9b3 (patch)
tree6acdf81dad39cd7c009764b4538beddb0a6d860a /2021/day07/src/main.rs
parent120d53c0ff20574866ce10fa0538fb8b0dd2ef82 (diff)
downloadaoc-64e22194d39d2914db1e3bf93c90de9e0791d9b3.tar.gz
aoc-64e22194d39d2914db1e3bf93c90de9e0791d9b3.zip
chore: reorganize project structure
Diffstat (limited to '2021/day07/src/main.rs')
-rw-r--r--2021/day07/src/main.rs28
1 files changed, 28 insertions, 0 deletions
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 @@
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}