-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday01.rs
88 lines (77 loc) · 2.53 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
85
86
87
88
use std::fs;
pub(crate) fn day01() {
println!("{}", part_a(fs::read_to_string("input/2023/day01/input.txt").unwrap()));
println!("{}", part_b(fs::read_to_string("input/2023/day01/input.txt").unwrap()));
}
fn part_a(elves: String) -> u32 {
return elves.lines().map(|line| {
let mut has_first = false;
let mut first = 0;
let mut last = 0;
for x in line.chars() {
if x.is_digit(10) {
let z = x.to_digit(10).unwrap();
if !has_first {
has_first = true;
first = z;
}
last = z;
}
}
first * 10 + last
}).sum();
}
fn part_b(elves: String) -> u32 {
return elves.lines().map(|l| {
let mut line = l;
let mut nums = vec!();
while line.len() > 0 {
if line.starts_with("1") || line.starts_with("one") {
nums.push(1);
}
if line.starts_with("2") || line.starts_with("two") {
nums.push(2);
}
if line.starts_with("3") || line.starts_with("three") {
nums.push(3);
}
if line.starts_with("4") || line.starts_with("four") {
nums.push(4);
}
if line.starts_with("5") || line.starts_with("five") {
nums.push(5);
}
if line.starts_with("6") || line.starts_with("six") {
nums.push(6);
}
if line.starts_with("7") || line.starts_with("seven") {
nums.push(7);
}
if line.starts_with("8") || line.starts_with("eight") {
nums.push(8);
}
if line.starts_with("9") || line.starts_with("nine") {
nums.push(9);
}
line = &line[1..]
}
10 * nums.first().unwrap() + nums.last().unwrap()
}).sum();
}
#[cfg(test)]
mod day01_tests {
use std::fs;
use crate::y2023::day01::{part_a, part_b};
#[test]
fn test_works() {
let input_a = fs::read_to_string("input/2023/day01/test.txt").unwrap();
assert_eq!(142, part_a(input_a));
let input_b = fs::read_to_string("input/2023/day01/test-b.txt").unwrap();
assert_eq!(281, part_b(input_b));
}
#[test]
fn input_works() {
assert_eq!(54990, part_a(fs::read_to_string("input/2023/day01/input.txt").unwrap()));
assert_eq!(54473, part_b(fs::read_to_string("input/2023/day01/input.txt").unwrap()));
}
}