diff options
author | Gard Spreemann <gspr@nonempty.org> | 2021-12-09 17:25:04 +0100 |
---|---|---|
committer | Gard Spreemann <gspr@nonempty.org> | 2021-12-09 17:25:04 +0100 |
commit | 53184c5377320b96455614e2010089a27ae3aba4 (patch) | |
tree | 1d88608237b03d8ad3df5bc77945fdd6710012d9 /07/src/part-1.rs | |
parent | 0893f9a3c187a4e6e7d74764f2c5dbd6579391d7 (diff) |
Day 7
Diffstat (limited to '07/src/part-1.rs')
-rw-r--r-- | 07/src/part-1.rs | 27 |
1 files changed, 27 insertions, 0 deletions
diff --git a/07/src/part-1.rs b/07/src/part-1.rs new file mode 100644 index 0000000..db20c41 --- /dev/null +++ b/07/src/part-1.rs @@ -0,0 +1,27 @@ +use std::io::{BufRead}; + +fn cost(positions: & [i64], dest: i64) -> i64 { + positions.into_iter().map(|x| (x - dest).abs()).sum() +} + +fn median<T: Copy + Ord>(mut x: Vec<T>) -> T { + let n = x.len(); + *x.select_nth_unstable(n/2).1 +} + +pub fn main() { + let mut stdin = std::io::stdin(); + let mut handle = stdin.lock(); + + let input: String = { + let mut buf = String::new(); + handle.read_line(&mut buf).unwrap(); + String::from(buf.trim_end()) + }; + + let positions: Vec<i64> = input.split(',').map(|w| w.parse().expect("Malformed input")).collect(); + let median = median(positions.clone()); + let cost = cost(& positions, median); + + println!("Align at {} for a cost of {}.", median, cost); +} |