From c20eb0ca69e6c62efe60271372513ed39f463da6 Mon Sep 17 00:00:00 2001 From: Samuel Ortion Date: Fri, 1 Dec 2023 13:40:17 +0100 Subject: [PATCH] day1 part2 solved --- days/.gitignore | 2 ++ days/01/part2/src/main.rs | 31 +++++++++++++++++++++++++++---- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/days/.gitignore b/days/.gitignore index 6985cf1..afea973 100755 --- a/days/.gitignore +++ b/days/.gitignore @@ -1,3 +1,5 @@ +data + # Generated by Cargo # will have compiled files and executables debug/ diff --git a/days/01/part2/src/main.rs b/days/01/part2/src/main.rs index 1f654a7..bfb3aee 100644 --- a/days/01/part2/src/main.rs +++ b/days/01/part2/src/main.rs @@ -1,3 +1,5 @@ +use std::cmp; +use std::collections::HashMap; use std::fs; // Extract all numbers, digits and letter written digits @@ -5,6 +7,26 @@ fn extract_numbers(line: &str) -> Vec { let written_digits: Vec<&str> = vec![ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", ]; + let mut max_tail_overlaps: HashMap<&str, u32> = HashMap::new(); + // Compute the size of the suffix of number i overlaping with prefix of number j: + for suffix_number in &written_digits { + max_tail_overlaps.insert(suffix_number.clone(), 0); + for prefix_number in &written_digits { + if suffix_number != prefix_number { + let mut overlap: u32 = 0; + for i in 0..(cmp::min(prefix_number.len(), suffix_number.len())) { + if suffix_number.chars().nth_back(i) == prefix_number.chars().nth(i) { + overlap += 1; + } else { + break; + } + } + if overlap > max_tail_overlaps[suffix_number] { + max_tail_overlaps.insert(suffix_number, overlap); + } + } + } + } let mut numbers: Vec = Vec::new(); let mut current_digit_word: String = "".to_owned(); for character in line.chars() { @@ -19,12 +41,13 @@ fn extract_numbers(line: &str) -> Vec { let positions: Vec<(usize, &str)> = current_digit_word.match_indices(digit_writing).collect(); if positions.len() > 0 { - let start_position = positions[0].0; - let end_position = start_position + word_length; - let current_digit_word_slice = ¤t_digit_word[end_position..]; - current_digit_word = current_digit_word_slice.to_owned(); let digit = index as u32 + 1; numbers.push(digit); + let start_position = positions[0].0; + let end_position = + start_position + word_length - max_tail_overlaps[digit_writing] as usize; + let current_digit_word_slice = ¤t_digit_word[end_position..]; + current_digit_word = current_digit_word_slice.to_owned(); } } }