From 35069272ca00f80292b1703f0c595e067aeb3249 Mon Sep 17 00:00:00 2001 From: Kevin Caffrey Date: Fri, 1 Dec 2023 14:14:35 -0500 Subject: [PATCH] optimize day 1 --- README.md | 4 ++-- src/bin/01.rs | 28 ++++++++++++++++++---------- 2 files changed, 20 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 7df2cc0..c79963e 100644 --- a/README.md +++ b/README.md @@ -17,9 +17,9 @@ Solutions for [Advent of Code](https://adventofcode.com/) in [Rust](https://www. | Day | Part 1 | Part 2 | | :---: | :---: | :---: | -| [Day 1](./src/bin/01.rs) | `39.5µs` | `1.1ms` | +| [Day 1](./src/bin/01.rs) | `40.4µs` | `80.7µs` | -**Total: 1.14ms** +**Total: 0.12ms** --- diff --git a/src/bin/01.rs b/src/bin/01.rs index 31d56ae..579530a 100644 --- a/src/bin/01.rs +++ b/src/bin/01.rs @@ -40,16 +40,24 @@ pub fn part_two(input: &str) -> Option { .to_ascii_lowercase() .lines() .filter_map(|line| { - let first = digit_strs - .iter() - .filter_map(|&(s, val)| line.find(s).map(|index| (index, val))) - .min_by_key(|&(index, _)| index) - .map(|(_, val)| val); - let last = digit_strs - .iter() - .filter_map(|&(s, val)| line.rfind(s).map(|index| (index, val))) - .max_by_key(|&(index, _)| index) - .map(|(_, val)| val); + let first = (0..line.len()).find_map(|start| { + digit_strs.iter().find_map(|(digit_str, val)| { + if line[start..].starts_with(digit_str) { + Some(*val) + } else { + None + } + }) + }); + let last = (0..line.len()).rev().find_map(|end| { + digit_strs.iter().find_map(|(digit_str, val)| { + if line[..=end].ends_with(digit_str) { + Some(*val) + } else { + None + } + }) + }); first.zip(last).map(|(a, b)| a * 10 + b) }) .sum(),