-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday1.rs
80 lines (74 loc) · 2.09 KB
/
day1.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
use super::Solution;
pub struct Day1 {
input: String,
}
impl Solution for Day1 {
fn part1(&mut self) -> String {
self.input
.lines()
.map(|line| {
let mut iter = line.chars().filter_map(|digit| digit.to_digit(10));
let first = iter.next().unwrap();
let last = iter.last().unwrap_or(first);
first * 10 + last
})
.sum::<u32>()
.to_string()
}
fn part2(&mut self) -> String {
self.input
.lines()
.map(|line| {
let mut first = 0;
for i in 0..line.len() {
let digit = get_digit(&line[i..]);
if let Some(digit) = digit {
first = digit;
break;
}
}
let mut last = 0;
for i in (0..line.len()).rev() {
let digit = get_digit(&line[i..]);
if let Some(digit) = digit {
last = digit;
break;
}
}
first * 10 + last
})
.sum::<u32>()
.to_string()
}
fn parse(input: String) -> Box<dyn Solution> {
Box::new(Self { input })
}
}
fn get_digit(string: &str) -> Option<u32> {
if let Some(digit) = string.chars().next().unwrap().to_digit(10) {
return Some(digit);
}
if string.starts_with("one") {
Some(1)
} else if string.starts_with("two") {
Some(2)
} else if string.starts_with("three") {
Some(3)
} else if string.starts_with("four") {
Some(4)
} else if string.starts_with("five") {
Some(5)
} else if string.starts_with("six") {
Some(6)
} else if string.starts_with("seven") {
Some(7)
} else if string.starts_with("eight") {
Some(8)
} else if string.starts_with("nine") {
Some(9)
} else if string.starts_with("zero") {
Some(0)
} else {
None
}
}