finished day 01 part 2

This commit is contained in:
Kristofers Solo 2023-12-02 19:50:16 +02:00
parent efd556f72e
commit 1ab7c5779f
2 changed files with 1059 additions and 0 deletions

1000
day-01/input2.txt Normal file

File diff suppressed because it is too large Load Diff

59
day-01/src/part2.rs Normal file
View File

@ -0,0 +1,59 @@
use color_eyre::Result;
pub fn process(input: &str) -> Result<u32> {
let sum: u32 = input.lines().map(process_line).sum();
Ok(sum)
}
fn process_line(line: &str) -> u32 {
let mut it = (0..line.len()).filter_map(|index| {
let reduced_line = &line[index..];
let result = if reduced_line.starts_with("one") {
Some(1)
} else if reduced_line.starts_with("two") {
Some(2)
} else if reduced_line.starts_with("three") {
Some(3)
} else if reduced_line.starts_with("four") {
Some(4)
} else if reduced_line.starts_with("five") {
Some(5)
} else if reduced_line.starts_with("six") {
Some(6)
} else if reduced_line.starts_with("seven") {
Some(7)
} else if reduced_line.starts_with("eight") {
Some(8)
} else if reduced_line.starts_with("nine") {
Some(9)
} else {
reduced_line.chars().next().unwrap().to_digit(10)
};
result
});
let first = it.next().expect("Should be a number");
match it.last() {
Some(num) => first * 10 + num,
None => first * 10 + first,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_process() -> Result<()> {
let input = "two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen";
assert_eq!(281, process(input)?);
Ok(())
}
}