1
Fork 0

Solve day 6!

This commit is contained in:
Bauke 2021-12-06 12:16:13 +01:00
parent 7504eb8d8d
commit c2f7e68ad4
Signed by: Bauke
GPG Key ID: C1C0F29952BCF558
2 changed files with 74 additions and 0 deletions

72
source/day_06/mod.rs Normal file
View File

@ -0,0 +1,72 @@
use std::collections::HashMap;
use color_eyre::Result;
type FishMap = HashMap<isize, isize>;
pub fn solve() -> Result<()> {
let input_data = include_str!("../../data/day_06.txt").trim();
println!("Day 06 Part 1: {}", part_1(input_data)?);
println!("Day 06 Part 2: {}", part_2(input_data)?);
Ok(())
}
fn part_1(input: &str) -> Result<isize> {
let mut fishes = parse_fishes(input)?;
for _ in 0..80 {
fishes = simulate_fishes(fishes);
}
Ok(count_fishes(fishes))
}
fn part_2(input: &str) -> Result<isize> {
let mut fishes = parse_fishes(input)?;
for _ in 0..256 {
fishes = simulate_fishes(fishes);
}
Ok(count_fishes(fishes))
}
fn parse_fishes(input: &str) -> Result<FishMap> {
let mut fishes = FishMap::new();
let individual_fishes = input
.split(",")
.map(str::parse)
.collect::<Result<Vec<_>, _>>()?;
for fish in individual_fishes {
let amount = fishes.entry(fish).or_default();
*amount += 1;
}
Ok(fishes)
}
fn count_fishes(fishes: FishMap) -> isize {
fishes.into_iter().map(|(_, amount)| amount).sum()
}
fn simulate_fishes(fishes: FishMap) -> FishMap {
let mut new_fishes = HashMap::new();
for (mut timer, amount) in fishes {
timer -= 1;
if timer < 0 {
let new_fish = new_fishes.entry(8).or_default();
*new_fish += amount;
let reset_fish = new_fishes.entry(6).or_default();
*reset_fish += amount;
} else {
let current_fish = new_fishes.entry(timer).or_default();
*current_fish += amount;
}
}
new_fishes
}

View File

@ -7,6 +7,7 @@ mod day_02;
mod day_03;
mod day_04;
mod day_05;
mod day_06;
fn main() -> Result<()> {
color_eyre::install()?;
@ -19,6 +20,7 @@ fn main() -> Result<()> {
day_03::solve,
day_04::solve,
day_05::solve,
day_06::solve,
];
for day in days {