solution: day 1 clean

This commit is contained in:
Matej Janezic 2023-12-01 06:53:06 +01:00
parent 00000030a5
commit 000000402b
Signed by: janezicmatej
GPG Key ID: 4298E230ED37B2C0
1 changed files with 23 additions and 17 deletions

View File

@ -1,18 +1,21 @@
pub fn part_one(input: &str) -> Option<u32> { pub fn part_one(input: &str) -> Option<u32> {
let mut c = 0; let mut c = 0;
for line in input.lines() { for line in input.lines() {
let mut itr = line.chars().filter(|x| x.is_ascii_digit()); let mut itr = line.chars().filter(char::is_ascii_digit);
let f = itr.next().unwrap(); let first = itr.next().unwrap();
let l = itr.last().unwrap_or(f); let last = itr.last().unwrap_or(first);
c += format!("{f}{l}").parse::<u32>().unwrap(); c += format!("{first}{last}").parse::<u32>().unwrap();
} }
Some(c) Some(c)
} }
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
let mut c = 0; let mut c = 0;
let nums = [ let nums = [
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
@ -41,14 +44,15 @@ pub fn part_two(input: &str) -> Option<u32> {
last = (m.0, Some(idx + 1)); last = (m.0, Some(idx + 1));
} }
} }
let mut itr = line.chars().enumerate().filter(|(_, x)| x.is_ascii_digit());
let Some(f) = itr.next() else { let mut itr = line
c += format!("{}{}", first.1.unwrap(), last.1.unwrap()) .chars()
.parse::<u32>() .enumerate()
.unwrap(); .filter(|(_, x)| x.is_ascii_digit())
continue; .peekable();
};
if itr.peek().is_some() {
let f = itr.next().unwrap();
let l = itr.last().unwrap_or(f); let l = itr.last().unwrap_or(f);
if f.0 < first.0 { if f.0 < first.0 {
@ -58,6 +62,8 @@ pub fn part_two(input: &str) -> Option<u32> {
if l.0 >= last.0 { if l.0 >= last.0 {
last = (l.0, l.1.to_string().parse().ok()); last = (l.0, l.1.to_string().parse().ok());
} }
}
c += format!("{}{}", first.1.unwrap(), last.1.unwrap()) c += format!("{}{}", first.1.unwrap(), last.1.unwrap())
.parse::<u32>() .parse::<u32>()
.unwrap(); .unwrap();