From 54700e121b06d1472ee78daaab77cde23ba3c7ce Mon Sep 17 00:00:00 2001 From: Daniel Seiller Date: Tue, 7 Dec 2021 14:03:33 +0100 Subject: [PATCH] Day 6 optimized + Day 7 --- src/day06.rs | 25 +++++++++++++------------ src/day07.rs | 33 +++++++++++++++++++++++++++++++++ src/lib.rs | 3 +++ src/main.rs | 1 + 4 files changed, 50 insertions(+), 12 deletions(-) create mode 100644 src/day07.rs diff --git a/src/day06.rs b/src/day06.rs index 130716d..aec4af9 100644 --- a/src/day06.rs +++ b/src/day06.rs @@ -1,32 +1,33 @@ use aoc_runner_derive::{aoc, aoc_generator}; -type Data = Vec; +type Data = [usize;9]; #[aoc_generator(day06)] -pub fn input_generator(input: &str) -> Data { - input.trim().split(',').map(|v| v.parse().unwrap()).collect() +pub fn input_generator(input: &str) -> [usize;9] { + let mut state: [usize;9] = [0;9]; + let input = input.trim().split(',').map(|v| v.parse::().unwrap()); + for v in input { + state[v]+=1; + } + state } fn simulate(input: &Data,n: usize) -> usize { - let mut state: [usize;9] = [0;9]; - for v in input { - state[*v as usize]+=1; - } - for _ in 0..n { - state[7]+=state[0]; - state.rotate_left(1); + let mut state=*input; + for i in 0..n { + state[(7+i)%9]+=state[i%9]; } state.iter().sum() } -#[aoc(day06, part1)] +#[aoc(day06, part1)] // 353274 pub fn solve_part1(input: &Data) -> usize { simulate(input,80) } -#[aoc(day06, part2)] +#[aoc(day06, part2)] // 1609314870967 pub fn solve_part2(input: &Data) -> usize { simulate(input,256) } diff --git a/src/day07.rs b/src/day07.rs new file mode 100644 index 0000000..ed57742 --- /dev/null +++ b/src/day07.rs @@ -0,0 +1,33 @@ +use aoc_runner_derive::{aoc, aoc_generator}; + +type Data = Vec; + +#[aoc_generator(day07)] +pub fn input_generator(input: &str) -> Data { + let mut input: Vec<_> = input.split(',').map(|v| v.parse().unwrap()).collect(); + input.sort_unstable(); + input +} + +#[aoc(day07, part1)] // 336040 +pub fn solve_part1(input: &Data) -> i64 { + let start = *input.first().unwrap(); + let end = *input.last().unwrap(); + (start..=end).map(|n| { + input.iter().map(|v| { + (v-n).abs() + }).sum() + }).min().unwrap() +} + +#[aoc(day07, part2)] // 94813675 +pub fn solve_part2(input: &Data) -> i64 { + let start = *input.first().unwrap(); + let end = *input.last().unwrap(); + (start..=end).map(|n| { + input.iter().map(|v| { + let diff=(v-n).abs(); + (diff*(diff+1))>>1 // Gauss + }).sum() + }).min().unwrap() +} diff --git a/src/lib.rs b/src/lib.rs index 233721f..eb52f7a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,6 @@ #![allow(clippy::clippy::needless_return)] +#![feature(int_abs_diff)] + use aoc_runner_derive::aoc_lib; pub mod day01; pub mod day02; @@ -6,4 +8,5 @@ pub mod day03; pub mod day04; pub mod day05; pub mod day06; +pub mod day07; aoc_lib! { year = 2021 } diff --git a/src/main.rs b/src/main.rs index 428818a..9ba1387 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,2 +1,3 @@ +#![feature(int_abs_diff)] use aoc_runner_derive::aoc_main; aoc_main! { lib = aoc_2021 }