From e1e03896d5a61d5c311a92b29c6d50640df1015c Mon Sep 17 00:00:00 2001 From: Ishan Jain Date: Fri, 1 Dec 2023 15:04:54 +0530 Subject: [PATCH] optimized day1 --- src/day1/2.rs | 97 ++++++++++++++++++++++++++++----------------------- 1 file changed, 53 insertions(+), 44 deletions(-) diff --git a/src/day1/2.rs b/src/day1/2.rs index e8d3c9e..2b308b8 100644 --- a/src/day1/2.rs +++ b/src/day1/2.rs @@ -7,51 +7,10 @@ fn process(data: &str) -> u64 { let mut total: u64 = 0; for line in data.split('\n') { - let mut first = 0; - let mut last = 0; + let line: Vec = line.chars().collect(); - let mut window = Vec::with_capacity(line.len()); - let mut j = 0; - - for (i, c) in line.chars().enumerate() { - if (window.len() - j) >= 5 { - j += 1; - } - - match c { - v @ '1'..='9' if first == 0 => { - let num = v as u8 - b'0'; - first = 10 * num; - last = num; - - j = i + 1; - } - v @ '1'..='9' => { - let num = v as u8 - b'0'; - last = num; - - j = i + 1; - } - _ => (), - } - window.push(c); - - if window.len() - j >= 3 { - if let Some(digit) = get_digit(&window[j..]) { - if first == 0 { - first = 10 * digit; - } - last = digit; - } - } - } - - if let Some(digit) = get_digit(&window[j..]) { - if first == 0 { - first = 10 * digit; - } - last = digit; - } + let first = 10 * find_forward(&line); + let last = find_backward(&line); total += first as u64 + last as u64; } @@ -59,6 +18,56 @@ fn process(data: &str) -> u64 { total } +fn find_forward(iter: &[char]) -> u8 { + let mut start = 0; + let mut end = 0; + + for c in iter.iter() { + if ('1'..='9').contains(c) { + return *c as u8 - b'0'; + } + + if end - start >= 5 { + start += 1; + } + end += 1; + + if end - start >= 3 { + if let Some(digit) = get_digit(&iter[start..end]) { + return digit; + } + } + } + + get_digit(&iter[start..end]).unwrap_or(0) +} +fn find_backward(iter: &[char]) -> u8 { + if iter.is_empty() { + return 0; + } + let mut start = iter.len() - 1; + let mut end = iter.len(); + + for c in iter.iter().rev() { + if ('1'..='9').contains(c) { + return *c as u8 - b'0'; + } + if end - start >= 5 { + end -= 1; + } + + start -= 1; + + if end - start >= 3 { + if let Some(digit) = get_digit(&iter[start..end]) { + return digit; + } + } + } + + get_digit(&iter[start..end]).unwrap_or(0) +} + fn main() { for input in INPUTS.iter() { println!("total = {}", process(input));