-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday01.rs
84 lines (72 loc) · 2.08 KB
/
day01.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use aoc_lib::{answer::Answer, solution::Solution};
pub struct Day1;
impl Solution for Day1 {
fn part_a(&self, input: &[String]) -> Answer {
let result: u32 = input
.iter()
.map(|l| {
let mut digits = l.chars().filter_map(|c| c.to_digit(10));
let first = digits.next().unwrap();
let last = digits.last().unwrap_or(first);
first * 10 + last
})
.sum();
result.into()
}
fn part_b(&self, input: &[String]) -> Answer {
let result: u32 = input
.iter()
.map(|l| {
let digits = get_digits(l);
digits[0] * 10 + digits[1]
})
.sum();
result.into()
}
}
fn get_digits(i: &str) -> [u32; 2] {
let helper = [
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
];
let mut first = None;
let mut last = 0;
let mut digit = |c| {
first = first.or(Some(c));
last = c;
};
let chars = i.as_bytes();
let mut i = 0;
while i < chars.len() {
let c = chars[i];
if c.is_ascii_digit() {
digit((c - b'0') as u32);
} else {
for (j, d) in helper.iter().enumerate() {
if chars[i..].starts_with(d.as_bytes()) {
digit(j as u32 + 1);
}
}
}
i += 1;
}
[first.unwrap(), last]
}
#[cfg(test)]
mod test {
use aoc_lib::{answer::Answer, input, solution::Solution};
use super::Day1;
#[test]
fn test_a() {
let input =
input::read_file(&format!("{}day_01_a_test.txt", crate::FILES_PREFIX_TEST)).unwrap();
let answer = Day1.part_a(&input);
assert_eq!(<i32 as Into<Answer>>::into(142), answer);
}
#[test]
fn test_b() {
let input =
input::read_file(&format!("{}day_01_b_test.txt", crate::FILES_PREFIX_TEST)).unwrap();
let answer = Day1.part_b(&input);
assert_eq!(<i32 as Into<Answer>>::into(281), answer);
}
}