2021-12-07 11:57:45 +01:00
#![ feature(int_abs_diff) ]
#![ feature(test) ]
extern crate test ;
use aoc2021 ::common ::* ;
const DAY : usize = 7 ;
type Parsed = Vec < usize > ;
fn parse_input ( raw : & str ) -> Parsed {
parse_nums_comma ( raw )
}
fn part1 ( parsed : & Parsed ) -> usize {
2021-12-07 14:06:09 +01:00
let mut nums = parsed . to_owned ( ) ;
2021-12-07 19:43:24 +01:00
let median = * nums . select_nth_unstable ( parsed . len ( ) / 2 ) . 1 ;
2021-12-07 14:06:09 +01:00
parsed . iter ( ) . map ( | p | p . abs_diff ( median ) ) . sum ( )
2021-12-07 11:57:45 +01:00
}
fn part2 ( parsed : & Parsed ) -> usize {
2021-12-07 14:06:09 +01:00
let avg = parsed . iter ( ) . sum ::< usize > ( ) / parsed . len ( ) ;
parsed . iter ( ) . map ( | p | p . abs_diff ( avg ) ) . map ( | n | ( 0 ..= n ) . sum ::< usize > ( ) ) . sum ( )
2021-12-07 11:57:45 +01:00
}
fn main ( ) {
let input = parse_input ( & read_file ( DAY ) ) ;
println! ( " Part 1: {} " , part1 ( & input ) ) ;
println! ( " Part 2: {} " , part2 ( & input ) ) ;
}
#[ cfg(test) ]
mod tests {
use super ::* ;
use aoc2021 ::* ;
const TEST_INPUT : & str = " 16,1,2,0,4,2,7,1,2,14 " ;
test! ( part1 ( ) = = 37 ) ;
bench! ( part1 ( ) = = 328318 ) ;
bench! ( part2 ( ) = = 89791146 ) ;
bench_input! ( Vec ::len = > 1000 ) ;
}