[TASK] Day 2

This commit is contained in:
2023-12-02 16:13:34 +01:00
parent a23008922f
commit 13263f6f05
4 changed files with 178 additions and 1 deletions

69
src/day2.rs Normal file
View File

@@ -0,0 +1,69 @@
use crate::day_solver::DaySolver;
use super::util;
pub struct Day2 {
games: Vec<Game>
}
struct Game {
id: u32,
turns: Vec<Turn>
}
struct Turn {
red: u32,
green: u32,
blue: u32
}
impl Day2 {
pub fn create() -> Self {
return Day2 {
games: util::read_file("input/day2.txt").iter()
.map(|s| {
let mut s_spl = s.split(": ");
let game_id: u32 = s_spl.next().unwrap()[5..].parse().unwrap();
Game {
id: game_id,
turns: s_spl.next().unwrap().split("; ")
.map(|turn_str| {
let turn_parts: Vec<(u32, &str)> = turn_str.split(", ").map(|t| {
let mut t_spl = t.split(" ");
(t_spl.next().unwrap().parse().unwrap(), t_spl.next().unwrap())
}).collect();
Turn {
red: turn_parts.iter().find(|t| t.1 == "red").map(|t| t.0).unwrap_or(0),
green: turn_parts.iter().find(|t| t.1 == "green").map(|t| t.0).unwrap_or(0),
blue: turn_parts.iter().find(|t| t.1 == "blue").map(|t| t.0).unwrap_or(0),
}
})
.collect()
}
}).collect()
}
}
}
impl DaySolver for Day2 {
fn solve_part1(&mut self) -> String {
return self.games.iter()
.filter(|g| g.turns.iter().all(|t| t.red <= 12 && t.green <= 13 && t.blue <= 14))
.map(|g| g.id)
.sum::<u32>().to_string()
}
fn solve_part2(&mut self) -> String {
return self.games.iter()
// Find the minimum number of cubes (which is the maximum of each turn), and multiply them together
.map(|g|
g.turns.iter().map(|t| t.red).max().unwrap() *
g.turns.iter().map(|t| t.green).max().unwrap() *
g.turns.iter().map(|t| t.blue).max().unwrap())
.sum::<u32>().to_string()
}
}

View File

@@ -2,13 +2,15 @@ extern crate core;
use std::time::Instant;
use crate::day1::Day1;
use crate::day2::Day2;
use crate::day_solver::DaySolver;
mod util;
mod day1;
mod day2;
mod day_solver;
const MAX_DAY: u8 = 1;
const MAX_DAY: u8 = 2;
const DEFAULT_BENCHMARK_AMOUNT: u32 = 100;
fn main() {
@@ -73,6 +75,7 @@ struct AocBenchResult {
fn build_day_solver(day: u8) -> Option<Box<dyn DaySolver>> {
match day {
1 => Some(Box::new(Day1::create())),
2 => Some(Box::new(Day2::create())),
_ => None
}
}