summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGard Spreemann <gspr@nonempty.org>2021-12-08 16:26:53 +0100
committerGard Spreemann <gspr@nonempty.org>2021-12-08 16:31:28 +0100
commit0893f9a3c187a4e6e7d74764f2c5dbd6579391d7 (patch)
tree9989b794abfc85de1eb4444103a48d19ed261ba2
parentd49d6dabc7c66263ae630de07a5ccf23a5c66c76 (diff)
Improve an embarassingly stupid day 6
-rw-r--r--06/src/part-1.rs6
-rw-r--r--06/src/part-2.rs36
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<String> = 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<String> = 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<FishSchool> = 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::<usize>().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::<usize>() + newborn_counts.into_iter().sum::<usize>());
}