From 9988056b093b3b3f4269562da4c780d55cd4688a Mon Sep 17 00:00:00 2001 From: Luca Matei Pintilie Date: Fri, 8 Dec 2023 18:57:18 +0100 Subject: Fix part 2 --- 2023/day1/src/main.rs | 59 ++++++++++++++++++++++++++------------------------- 1 file changed, 30 insertions(+), 29 deletions(-) diff --git a/2023/day1/src/main.rs b/2023/day1/src/main.rs index af457cd..9d277df 100644 --- a/2023/day1/src/main.rs +++ b/2023/day1/src/main.rs @@ -1,3 +1,5 @@ +use std::collections::HashMap; + fn main() { example_1(); example_2(); @@ -40,23 +42,29 @@ struct NumberInString { index: usize, } -const NUMBERS_AS_WORDS: [&str; 10] = [ - "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", -]; - -const NUMBERS_AS_NUMBERS: [usize; 10] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; - fn part_2(input: &str) -> usize { + let word_number_map: HashMap<&str, usize> = HashMap::from([ + ("one", 1), + ("two", 2), + ("three", 3), + ("four", 4), + ("five", 5), + ("six", 6), + ("seven", 7), + ("eight", 8), + ("nine", 9), + ]); + let mut sum = 0; for line in input.split('\n') { let mut nums: Vec = vec![]; - for word in NUMBERS_AS_WORDS { - if let Some(n) = get_index_of_word_number(line, word) { + for (word, number) in word_number_map.clone() { + for n in get_index_of_word_number(line, word, number) { nums.push(n); } } - for number in NUMBERS_AS_NUMBERS { - if let Some(n) = get_index_of_number_number(line, number) { + for number in 0..10 { + for n in get_index_of_number_number(line, number) { nums.push(n); } } @@ -80,33 +88,26 @@ fn part_2(input: &str) -> usize { panic!("Undefined"); } let out = (min.number * 10) + max.number; - // println!("{0}, {1}, {2:?}", line, out, debug_nums); + // println!("{0}, {1}, {2:?}", line, out, nums); sum += out; } sum } -fn get_index_of_number_number(input: &str, number: usize) -> Option { - if let Some(num) = input.find(number.to_string().as_str()) { - return Some(NumberInString { - number: NUMBERS_AS_NUMBERS - .iter() - .position(|w| w == &number) - .unwrap(), - index: num, - }); +fn get_index_of_number_number(input: &str, number: usize) -> Vec { + let mut out = vec![]; + for (num, _) in input.match_indices(number.to_string().as_str()) { + out.push(NumberInString { number, index: num }); } - None + out } -fn get_index_of_word_number(input: &str, word: &str) -> Option { - if let Some(num) = input.find(word) { - return Some(NumberInString { - number: NUMBERS_AS_WORDS.iter().position(|w| w == &word).unwrap(), - index: num, - }); +fn get_index_of_word_number(input: &str, word: &str, number: usize) -> Vec { + let mut out = vec![]; + for (num, _) in input.match_indices(word) { + out.push(NumberInString { number, index: num }); } - None + out } fn example_1() { @@ -139,7 +140,7 @@ fn task_1() { fn task_2() { let out = part_2(TASK); - assert_eq!(out, 57325); + assert_eq!(out, 57345); } const TASK: &str = r"two65eightbkgqcsn91qxkfvg -- cgit v1.2.3