generated from fspoettel/advent-of-code-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path07.rs
77 lines (71 loc) · 2.14 KB
/
07.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
advent_of_code::solution!(7);
fn solves(target: i64, values: &[i64], part2: bool) -> bool {
if values.len() == 1 {
return values[0] == target;
}
if let Some((last, rest)) = values.split_last() {
if target % last == 0 && solves(target / last, rest, part2) {
return true;
}
if target >= *last && solves(target - last, rest, part2) {
return true;
}
if part2 {
let mask = 10i64.pow(last.ilog10() + 1);
if target % mask == *last && solves(target / mask, rest, part2) {
return true;
}
}
};
false
}
pub fn part_one(input: &str) -> Option<i64> {
Some(
input
.lines()
.filter_map(|lines| lines.split_once(": "))
.map(|(test, values)| {
let test = test.parse::<i64>().unwrap();
let nums = values
.split_whitespace()
.filter_map(|n| n.parse::<i64>().ok())
.collect::<Vec<_>>();
(test, nums)
})
.filter(|(test, nums)| solves(*test, nums, false))
.map(|(a, _)| a)
.sum(),
)
}
pub fn part_two(input: &str) -> Option<i64> {
Some(
input
.lines()
.filter_map(|lines| lines.split_once(": "))
.map(|(test, values)| {
let test = test.parse::<i64>().unwrap();
let nums = values
.split_whitespace()
.filter_map(|n| n.parse::<i64>().ok())
.collect::<Vec<_>>();
(test, nums)
})
.filter(|(test, nums)| solves(*test, nums, true))
.map(|(a, _)| a)
.sum(),
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part_one() {
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(3749));
}
#[test]
fn test_part_two() {
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(11387));
}
}