optimized day1

This commit is contained in:
Ishan Jain 2023-12-01 15:04:54 +05:30
parent 7474d03451
commit e1e03896d5
Signed by: ishan
GPG Key ID: 0506DB2A1CC75C27

View File

@ -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<char> = 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));