day2 part1

This commit is contained in:
2024-09-16 20:00:40 +02:00
parent 70d4df91ea
commit 00e06586e8
3 changed files with 221 additions and 2 deletions

View File

@@ -1,3 +1,90 @@
fn main() {
println!("Hello, world!");
use std::{collections::HashMap, fs::File, io::{self, BufRead}, path::Path};
//struct to hold the game's information
#[derive(Debug)]
struct Game{
game_num: i32,
all_draws: Draws,
}
// struct to hold info of the elf drawing from its bag and showing us
// each time the elf draws from the bag we convert that into a hashmap,
// to have direct access from the color string to the amount
#[derive(Debug)]
struct Draws{
draws: Vec<HashMap<String,i32>>,
}
fn main() {
// File hosts.txt must exist in the current path
if let Ok(lines) = read_lines("./input") {
let mut result = 0;
// Consumes the iterator, returns an (Optional) String
for line in lines.flatten() {
let game = parse_line(&line);
println!("{game:?}");
println!("{line}");
let mut rule_break:bool = false;
for draw in game.all_draws.draws{
match draw.get("red"){
Some(amount) => if amount.gt(&12) {println!("{amount} > 12");rule_break = true; continue;},
None => (),
}
match draw.get("green"){
Some(amount) => if amount.gt(&13) {println!("{amount} > 13");rule_break = true; continue;},
None => (),
}
match draw.get("blue"){
Some(amount) => if amount.gt(&14) {println!("{amount} > 14");rule_break = true; continue;},
None => (),
}
}
if !rule_break{
result+=game.game_num
}
}
println!("{result}");
}
}
// parses the whole line and splits it into smaller parts to be inspected further by other functions
fn parse_line<T: AsRef<str>>(input: T) -> Game {
let parts = input.as_ref().split(": ").collect::<Vec<&str>>();
let game_string = parts[0];
let game_num = game_string.split(" ").collect::<Vec<&str>>()[1];
let all_draws = get_all_draws(&parts[1]);
Game{
game_num: game_num.parse::<i32>().unwrap(),
all_draws: all_draws,
}
}
fn get_all_draws(game_str: &str) -> Draws {
let draws_str = game_str.split("; ").collect::<Vec<&str>>();
let mut draws: Vec<HashMap<String,i32>> = Vec::new();
for draw in draws_str{
draws.push(get_draws(draw));
}
Draws{
draws: draws,
}
}
fn get_draws<T: AsRef<str>>(input: T) -> HashMap<String,i32> {
let draws = input.as_ref().split(", ").collect::<Vec<&str>>();
let mut hm = HashMap::new();
for draw_part in draws {
let draw_parts = draw_part.split(" ").collect::<Vec<&str>>();
hm.insert(String::from(draw_parts[1]), draw_parts[0].parse::<i32>().unwrap().clone());
}
return hm;
}
// The output is wrapped in a Result to allow matching on errors.
// Returns an Iterator to the Reader of the lines of the file.
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())
}