From 3a87c137503984ae1e2314af5ffb462e47f31051 Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Fri, 8 Dec 2023 11:25:00 -0500 Subject: [PATCH] Parse the puzzle input for 2023 day 4 --- 2023/day4/src/main.rs | 37 ++++++++++++++++++++++++++++--------- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/2023/day4/src/main.rs b/2023/day4/src/main.rs index 47ddaed..529d362 100644 --- a/2023/day4/src/main.rs +++ b/2023/day4/src/main.rs @@ -1,8 +1,9 @@ use std::collections::HashMap; +use std::iter::FromIterator; const FILE_STR: &'static str = include_str!("input.txt"); -#[derive(Default)] +#[derive(Default, Debug)] struct ScratchCard { winning: Vec, chosen: Vec, @@ -16,18 +17,36 @@ impl ScratchCard { type GameMap = HashMap; +/// Parse numbers from a line, separated/surrounded by whitespace +fn parse_num_str(s: &str) -> Vec { + s.split_ascii_whitespace() + .filter(|s| s.len() > 0) + .map(|s| s.trim()) + .map(|s| usize::from_str_radix(s, 10).unwrap()) + .collect::>() +} + +fn parse_game_table_line(line: &str) -> (usize, ScratchCard) { + let parts: Vec<&str> = line.split(": ").collect(); + let card_num_parts = parts[0].replace("Card", ""); + let card_num = parse_num_str(&card_num_parts)[0]; + let nums: Vec> = parts[1].split(" | ").map(parse_num_str).collect(); + + (card_num, ScratchCard::new(nums[0].clone(), nums[1].clone())) +} + fn parse_game_table(table: &str) -> GameMap { - let mut map = HashMap::new(); - - table.split('\n').for_each(|line| { - todo!(); - }); - - map + HashMap::from_iter( + table + .split('\n') + .filter(|s| s.len() > 0) + .map(parse_game_table_line), + ) } fn part_one() { - todo!(); + let map = parse_game_table(FILE_STR); + println!("{:#?}", map); } fn main() {