advent-of-code/src/2023/02-cube-conundrum/part_one.rs

62 lines
1.4 KiB
Rust

use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;
pub fn part_one() {
if let Ok(lines) = read_lines("./input.txt") {
let mut result = 0;
for line in lines {
result += process_line(&line.unwrap());
}
println!("{}", result);
}
}
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where
P: AsRef<Path>,
{
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}
fn process_line(s: &str) -> u32 {
let v: Vec<&str> = s.split(':').collect();
let game_id: u32 = v[0].split("Game ").collect::<Vec<&str>>()[1]
.parse::<u32>()
.unwrap();
let games: Vec<&str> = v[1].split(';').collect();
for game in games {
let valid_game = process_game(game);
if !valid_game {
return 0;
}
}
return game_id;
}
fn process_game(s: &str) -> bool {
let cubes: Vec<&str> = s.split(',').collect();
for cube in cubes {
let cube_parts: Vec<&str> = cube.trim().split(' ').collect();
let cube_num = cube_parts[0].parse::<u32>().unwrap();
if cube_parts[1] == "red" && cube_num > 12 {
return false;
} else if cube_parts[1] == "green" && cube_num > 13 {
return false;
} else if cube_parts[1] == "blue" && cube_num > 14 {
return false;
}
}
return true;
}