implement minor optimizations for day 2

This commit is contained in:
Russell Champoux committed 2025-12-05 11:28:06 -05:00
1 parent 37bf0f6a60
commit 14e7a7f6f5
2 files changed
+18 -24

No files matched your search

+16 -22
View File
@@ -5,15 +5,12 @@ pub fn part_one(input: &str) -> Option<u64> {
let mut sum: u64 = 0;
for range in input.split(',') {
// println!("Range is: {}", range);
let values = range.split('-').map(|v| v.trim().parse::<u64>().unwrap()).collect::<Vec<u64>>();
let values = range.split('-').map(|v| v.trim().parse::<u64>().unwrap()).collect_vec();
let start = values[0];
let end = values[1];
// println!("Range: {}-{}", start, end);
for n in start..=end {
for n in (start..=end).filter(|n| n.to_string().len() % 2 == 0) {
let s = n.to_string();
if s.chars().collect_vec().len() % 2 != 0 {
continue;
}
let first_half = &s[0..(s.len() / 2)];
let second_half = &s[(s.len() / 2)..s.len()];
if first_half == second_half {
@@ -29,29 +26,26 @@ pub fn part_two(input: &str) -> Option<u64> {
let mut sum: u64 = 0;
for range in input.split(',') {
// println!("Range is: {}", range);
let values = range.split('-').map(|v| v.trim().parse::<u64>().unwrap()).collect::<Vec<u64>>();
let values = range.split('-').map(|v| v.trim().parse::<u64>().unwrap()).collect_vec();
let start = values[0];
let end = values[1];
// println!("Range: {}-{}", start, end);
for n in start..=end {
let s = n.to_string();
let total_chars = s.chars().collect_vec().len();
'takeBy: for take_by in 1..=(total_chars / 2) {
if total_chars % take_by != 0 {
continue;
let total_chars = (n as f64).log10().floor() as usize + 1;
'takeBy: for take_by in (1..=(total_chars / 2)).filter(|tb| total_chars % tb == 0) {
let mut idx = 0;
while idx + 2 * take_by <= total_chars {
let part = &s[idx..(idx + take_by)];
let next_part = &s[(idx + take_by)..(idx + 2 * take_by)];
if part != next_part {
continue 'takeBy;
}
idx += take_by;
}
let mut idx = 0;
while idx + 2 * take_by <= total_chars {
let part = &s[idx..(idx + take_by)];
let next_part = &s[(idx + take_by)..(idx + 2 * take_by)];
if part != next_part {
continue 'takeBy;
}
idx += take_by;
}
// println!(" Number: {} (take by {})", n, take_by);
sum += n;
break; // do not continue checking other take_by values
// println!(" Number: {} (take by {})", n, take_by);
sum += n;
break; // do not continue checking other take_by values
}
}
}