generated from fspoettel/advent-of-code-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path07.rs
96 lines (83 loc) · 2.21 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
advent_of_code::solution!(7);
use itertools::Itertools;
fn parse_input(input: &str) -> Vec<Vec<u64>> {
input
.replace(":", "")
.lines()
.map(|line| {
line.split_whitespace()
.map(|s| s.parse().unwrap())
.collect()
})
.collect()
}
fn add(a: u64, b: u64) -> u64 {
a + b
}
fn mul(a: u64, b: u64) -> u64 {
a * b
}
fn concat(a: u64, b: u64) -> u64 {
a * 10_u64.pow(b.ilog10() as u32 + 1) + b
}
fn solve(mut values: Vec<u64>, mut ops: Vec<fn(u64, u64) -> u64>) -> u64 {
let result = ops[0](values[0], values[1]);
if values.len() == 2 {
return result;
}
// replace the 2 first values with the results of their operation
values[1] = result;
values.remove(0);
// remove the first operation
ops.remove(0);
solve(values, ops)
}
fn check_valid(values: Vec<u64>, incl_concat: bool) -> u64 {
let result = values[0];
let values_rest = values.into_iter().skip(1).collect::<Vec<u64>>();
let ops: Vec<fn(u64, u64) -> u64>;
if incl_concat {
ops = vec![add, mul, concat];
} else {
ops = vec![add, mul];
}
for equations in (0..values_rest.len() - 1)
.map(|_i| ops.clone())
.multi_cartesian_product()
{
//println!("{:?} = {}", values_rest, result);
if solve(values_rest.clone(), equations) == result {
//println!(" YES");
return result;
}
}
0
}
fn part_both(input: &str, incl_concat: bool) -> u64 {
let data = parse_input(input);
data.iter()
.map(|values| check_valid(values.clone(), incl_concat))
.sum()
}
pub fn part_one(input: &str) -> Option<u64> {
Some(part_both(input, false))
}
pub fn part_two(input: &str) -> Option<u64> {
Some(part_both(input, true))
}
#[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));
}
}