Skip to content

Commit e0fe991

Browse files
committed
chore: optimize by not using regex
1 parent dead762 commit e0fe991

File tree

3 files changed

+29
-31
lines changed

3 files changed

+29
-31
lines changed

Cargo.lock

Lines changed: 0 additions & 21 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

aoclp_solutions/Cargo.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ rust-version = "1.81.0"
88
aoclp = { path = "../aoclp" }
99
bit-vec = { workspace = true }
1010
clap = { workspace = true, features = ["derive"] }
11-
fancy-regex = { workspace = true }
1211
itertools = { workspace = true }
1312
paste = { workspace = true }
1413
primes = { workspace = true }

aoclp_solutions/src/y2025/day_02.rs

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,24 +3,21 @@ use std::str::FromStr;
33

44
use aoclp::num::Integer;
55
use aoclp::solvers_impl::input::safe_get_input_as_one_vec;
6-
use fancy_regex::Regex;
76
use itertools::Itertools;
87

98
pub fn part_1() -> usize {
10-
let re = Regex::new(r"^(\d+)\1$").unwrap();
11-
sum_of_invalid(&re)
9+
input()
10+
.into_iter()
11+
.flat_map(|range| range.into_iter())
12+
.filter(|id| invalid(*id))
13+
.sum()
1214
}
1315

1416
pub fn part_2() -> usize {
15-
let re = Regex::new(r"^(\d+)(\1)+$").unwrap();
16-
sum_of_invalid(&re)
17-
}
18-
19-
fn sum_of_invalid(re: &Regex) -> usize {
2017
input()
2118
.into_iter()
2219
.flat_map(|range| range.into_iter())
23-
.filter(|id| re.is_match(&id.to_string()).unwrap())
20+
.filter(|id| invalid_fancy(*id))
2421
.sum()
2522
}
2623

@@ -38,6 +35,29 @@ fn invalid(id: usize) -> bool {
3835
false
3936
}
4037

38+
fn invalid_fancy(id: usize) -> bool {
39+
let num_digits = num_digits(id);
40+
(1..=num_digits / 2).any(|of_size| invalid_of_size(id, num_digits, of_size))
41+
}
42+
43+
fn invalid_of_size(mut id: usize, num_digits: usize, of_size: usize) -> bool {
44+
if num_digits % of_size == 0 {
45+
let window = 10usize.pow(of_size as u32);
46+
let expected = id % window;
47+
while id != 0 {
48+
let actual = id % window;
49+
id /= window;
50+
if actual != expected {
51+
return false;
52+
}
53+
}
54+
55+
return true;
56+
}
57+
58+
false
59+
}
60+
4161
struct IdRange(RangeInclusive<usize>);
4262

4363
impl IntoIterator for IdRange {

0 commit comments

Comments
 (0)