blob: 8a44c072e9049aae315b2c7148cd18010d93dcfb (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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<i32> = 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::<i32>() 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) })
}
|