Skip to content

Commit

Permalink
optimize day 1
Browse files Browse the repository at this point in the history
  • Loading branch information
kcaffrey committed Dec 1, 2023
1 parent 070e251 commit 3506927
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 12 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**
<!--- benchmarking table --->

---
Expand Down
28 changes: 18 additions & 10 deletions src/bin/01.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,24 @@ pub fn part_two(input: &str) -> Option<u32> {
.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(),
Expand Down

0 comments on commit 3506927

Please sign in to comment.