solution: day 1 shorter version

This commit is contained in:
Matej Janezic 2023-12-02 14:54:55 +01:00
parent 000000701f
commit 00000080fc
Signed by: janezicmatej
GPG Key ID: 4298E230ED37B2C0
1 changed files with 17 additions and 43 deletions

View File

@ -13,60 +13,34 @@ pub fn part_one(input: &str) -> Option<u32> {
Some(c) Some(c)
} }
const NUMS: [&str; 9] = [
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
];
pub fn part_two(input: &str) -> Option<u32> { pub fn part_two(input: &str) -> Option<u32> {
// NOTE:(matej) this solution is O(n^2) since we search string for each substring separately // NOTE:(matej) this solution is O(n^2) since we search string for each substring separately
let mut c = 0; let mut c = 0;
let nums = [ let nums: Vec<(u32, String)> = (1..=9).zip(NUMS.into_iter().map(String::from)).collect();
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
];
for line in input.lines() { for line in input.lines() {
let mut first = (line.len(), None); let mut all_matches = Vec::new();
let mut last = (0, None);
for (idx, n) in nums.iter().enumerate() { for (n, str_n) in nums.iter() {
let matches: Vec<_> = line.match_indices(n).collect(); all_matches.extend(line.match_indices(str_n).map(|(x, _)| (x, *n)));
if matches.is_empty() {
continue;
}
let m = matches.first().unwrap();
if m.0 < first.0 {
first = (m.0, Some(idx + 1));
}
let m = matches.last().unwrap();
if m.0 >= last.0 {
last = (m.0, Some(idx + 1));
}
} }
let mut itr = line all_matches.extend(
.chars() line.chars()
.enumerate() .enumerate()
.filter(|(_, x)| x.is_ascii_digit()) .filter(|(_, c)| c.is_ascii_digit())
.peekable(); .map(|(idx, c)| (idx, c.to_digit(10).unwrap())),
);
if itr.peek().is_some() { let first = all_matches.iter().min_by_key(|&(idx, _)| idx).unwrap().1;
let f = itr.next().unwrap(); let last = all_matches.iter().max_by_key(|&(idx, _)| idx).unwrap().1;
let l = itr.last().unwrap_or(f);
if f.0 < first.0 { c += first * 10 + last;
first = (f.0, f.1.to_string().parse().ok());
}
if l.0 >= last.0 {
last = (l.0, l.1.to_string().parse().ok());
}
}
c += format!("{}{}", first.1.unwrap(), last.1.unwrap())
.parse::<u32>()
.unwrap();
} }
Some(c) Some(c)