day 1 part 2
This commit is contained in:
parent
7a7202d5c8
commit
f17c654135
1 changed files with 32 additions and 11 deletions
|
@ -6,28 +6,49 @@ fn main() {
|
|||
println!("Result: {}", result);
|
||||
}
|
||||
|
||||
fn calibration_value(input: &str) -> u32 {
|
||||
input.lines()
|
||||
.map(|line| {
|
||||
let digits: Vec<char> = line.chars().filter(|c| c.is_numeric()).collect();
|
||||
const VALUES: [&str; 18] = [
|
||||
"1", "2", "3", "4", "5", "6", "7", "8", "9", "one", "two", "three", "four", "five", "six",
|
||||
"seven", "eight", "nine",
|
||||
];
|
||||
|
||||
fn calibration_value(input: &str) -> u32 {
|
||||
input
|
||||
.lines()
|
||||
.map(|line| {
|
||||
let (_, first) = VALUES
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(vi, s)| line.find(s).map(|ri| (ri, (vi % 9) as u32 + 1)))
|
||||
.min_by_key(|(i, _v)| *i)
|
||||
.unwrap();
|
||||
let (_, last) = VALUES
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(vi, s)| line.rfind(s).map(|ri| (ri, (vi % 9) as u32 + 1)))
|
||||
.max_by_key(|(i, _v)| *i)
|
||||
.unwrap();
|
||||
|
||||
let first = digits.first().unwrap().to_digit(10).unwrap();
|
||||
let last = digits.last().unwrap().to_digit(10).unwrap();
|
||||
dbg!(first * 10 + last)
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::calibration_value;
|
||||
|
||||
const EXAMPLE: &str = "1abc2\npqr3stu8vwx\na1b2c3d4e5f\ntreb7uchet";
|
||||
const EXAMPLE_PART_1: &str = "1abc2\npqr3stu8vwx\na1b2c3d4e5f\ntreb7uchet";
|
||||
const EXAMPLE_PART_2: &str = "two1nine\neightwothree\nabcone2threexyz\nxtwone3four\n4nineeightseven2\nzoneight234\n7pqrstsixteen";
|
||||
|
||||
#[test]
|
||||
fn example() {
|
||||
let result = calibration_value(EXAMPLE);
|
||||
fn example_part_1() {
|
||||
let result = calibration_value(EXAMPLE_PART_1);
|
||||
assert_eq!(142, result);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn example_part_2() {
|
||||
let result = calibration_value(EXAMPLE_PART_2);
|
||||
assert_eq!(281, result);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue