Guest User

Untitled

a guest
Dec 7th, 2021
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.30 KB | None | 0 0
  1. fn aoc_07_part1(input: &mut Vec<i32>) -> i32 {
  2.     // Sorting so the median works...
  3.     input.sort();
  4.  
  5.     // input.len() % 2 will either be 0 or 1, which is what we want...
  6.     let middle = (input.len() + (input.len() % 2)) / 2;
  7.     // Get the median
  8.     let median = input[middle];
  9.  
  10.     // Sum of the abs of the elements vs the median gives the total consumption
  11.     input.iter().map(|el| i32::abs(el - median)).sum()
  12. }
  13.  
  14. fn aoc_07_part2(input: &Vec<i32>) -> i32 {
  15.     let mean = input.iter().sum::<i32>() / input.len() as i32;
  16.  
  17.     // It can be ranging from previous to next value so we need to do a -1, 0, 1
  18.     // and get the min of that range of values...
  19.     (-1..=1).into_iter().map(|epsilon| {
  20.         // Computing the total consumption for that epsilon
  21.         input.iter().map(|el| {
  22.             let val = i32::abs((*el) - mean + epsilon);
  23.             (val * (val + 1)) / 2
  24.         }).sum()
  25.     }).min().unwrap_or(0)
  26.  
  27. }
  28.  
  29. fn main() {
  30.     let line = include_str!("../input.txt").lines().next().unwrap_or("");
  31.     let mut s: Vec<i32> = line.split(',').filter_map(|s| s.parse::<i32>().ok()).collect::<Vec<i32>>();
  32.     let result = aoc_07_part1(&mut s);
  33.     println!("Total consumption: {}", result);
  34.     let result = aoc_07_part2(&s);
  35.     println!("New total consumption: {}", result);
  36. }
  37.  
Advertisement
Add Comment
Please, Sign In to add comment