From 0893f9a3c187a4e6e7d74764f2c5dbd6579391d7 Mon Sep 17 00:00:00 2001 From: Gard Spreemann Date: Wed, 8 Dec 2021 16:26:53 +0100 Subject: Improve an embarassingly stupid day 6 --- 06/src/part-1.rs | 6 ++++++ 06/src/part-2.rs | 36 ++++++++---------------------------- 2 files changed, 14 insertions(+), 28 deletions(-) diff --git a/06/src/part-1.rs b/06/src/part-1.rs index 5a1660e..f1723e1 100644 --- a/06/src/part-1.rs +++ b/06/src/part-1.rs @@ -1,5 +1,11 @@ use std::io::{BufRead}; +/* + * This is an embarassingly naïve solution based on poor reading of + * the problem and thinking that the actual example printout had to + * be reproduced. Part 2 is solved in a much saner way. + */ + pub fn main() { let args: Vec = std::env::args().collect(); if args.len() != 2 { panic!("Need exactly 1 argument"); } diff --git a/06/src/part-2.rs b/06/src/part-2.rs index 37d095e..c9ea499 100644 --- a/06/src/part-2.rs +++ b/06/src/part-2.rs @@ -1,11 +1,5 @@ use std::io::{BufRead}; -#[derive(Clone, Copy)] -struct FishSchool { - state: u64, - size: usize -} - pub fn main() { let args: Vec = std::env::args().collect(); if args.len() != 2 { panic!("Need exactly 1 argument"); } @@ -20,30 +14,16 @@ pub fn main() { String::from(buf.trim_end()) }; - let mut schools: Vec = input.split(',').map(|w| FishSchool { - state: w.parse().expect("Malformed input"), - size: 1} ).collect(); + // counts[i] is the number of fish that breed on days that are divisible by i. + let mut counts: [usize; 7] = [0; 7]; + let mut newborn_counts: [usize; 9] = [0; 9]; + input.split(',').map(|x| x.parse::().expect("Malformed input")).for_each(|x| counts[x % 7] += 1); for i in 0..num_days { - let mut new_fish_count: usize = 0; - for school in (&mut schools).into_iter() { - if school.state == 0 { - new_fish_count += school.size; - school.state = 6; - } - else { school.state -= 1; } - } - schools.push(FishSchool { state: 8, size: new_fish_count }); - - /* - print!("After day {:>width$}: ", i, width = format!("{}", num_days).len()); - for school in (& schools).into_iter() { - for _ in 0..school.size { print!("{} ", school.state); } - } - println!(""); - */ + let tmp = newborn_counts[i % 9]; + newborn_counts[i % 9] += counts[i % 7]; + counts[i % 7] += tmp; } - let n: usize = schools.into_iter().map(|school| school.size).sum(); - println!("After {} days there are {} fishies", num_days, n); + println!("After {} days there are {} fishiess", num_days, counts.into_iter().sum::() + newborn_counts.into_iter().sum::()); } -- cgit v1.2.3