Day 6 optimized + Day 7

This commit is contained in:
Daniel S. 2021-12-07 14:03:33 +01:00
parent 8b34e1bb1e
commit 54700e121b
4 changed files with 50 additions and 12 deletions

View file

@ -1,32 +1,33 @@
use aoc_runner_derive::{aoc, aoc_generator};
type Data = Vec<u8>;
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::<usize>().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)
}

33
src/day07.rs Normal file
View file

@ -0,0 +1,33 @@
use aoc_runner_derive::{aoc, aoc_generator};
type Data = Vec<i64>;
#[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()
}

View file

@ -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 }

View file

@ -1,2 +1,3 @@
#![feature(int_abs_diff)]
use aoc_runner_derive::aoc_main;
aoc_main! { lib = aoc_2021 }