Created
December 7, 2021 02:40
-
-
Save mszabo-wikia/2691bcc6700b8add2baef09e0f69f979 to your computer and use it in GitHub Desktop.
AoC 2021 Day 6
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use std::io; | |
| use std::str::FromStr; | |
| const FISH_REPRODUCTION_CYCLE: usize = 7; | |
| const FISH_INCUBATION_PERIOD: usize = 9; | |
| fn calc_fish_pop(fish_pop: &Vec<u32>, max_days: usize) { | |
| let mut fish_by_day: [u64; FISH_REPRODUCTION_CYCLE] = [0; FISH_REPRODUCTION_CYCLE]; | |
| let mut total_fish_count: u64 = 0; | |
| for fish in fish_pop { | |
| fish_by_day[*fish as usize] += 1; | |
| total_fish_count += 1; | |
| } | |
| let mut incubating_next_period: [u64; FISH_INCUBATION_PERIOD] = [0; FISH_INCUBATION_PERIOD]; | |
| let mut days = 0; | |
| while days < max_days { | |
| let cur_day = days % FISH_REPRODUCTION_CYCLE; | |
| fish_by_day[cur_day] += incubating_next_period[0]; | |
| let mut i = 0; | |
| while i < FISH_INCUBATION_PERIOD - 1 { | |
| incubating_next_period[i] = incubating_next_period[i + 1]; | |
| i += 1; | |
| } | |
| let num_reproducing_today = fish_by_day[cur_day]; | |
| incubating_next_period[FISH_INCUBATION_PERIOD - 1] = num_reproducing_today; | |
| total_fish_count += num_reproducing_today; | |
| days += 1; | |
| } | |
| println!("fish population after {} days: {}", max_days, total_fish_count); | |
| } | |
| fn main() { | |
| let mut line = String::new(); | |
| let stdin = io::stdin(); | |
| let mut fish_pop: Vec<u32> = vec![]; | |
| while stdin.read_line(&mut line).unwrap() > 0 { | |
| let mut parts = line.trim().split(','); | |
| while let Some(part) = parts.next() { | |
| let cur_fish = u32::from_str(part).unwrap(); | |
| fish_pop.push(cur_fish); | |
| } | |
| line.clear(); | |
| } | |
| calc_fish_pop(&fish_pop, 80); | |
| calc_fish_pop(&fish_pop, 256); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment