generated from fspoettel/advent-of-code-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
07.rs
128 lines (98 loc) · 3.01 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
advent_of_code::solution!();
fn parse(input: &str) -> impl Iterator<Item = (u64, impl Iterator<Item = u64> + '_)> {
input.lines().map(|line| {
let (result, values) = line.split_once(':').unwrap();
let result = result.parse().unwrap();
let values = values.split_whitespace().map(|n| n.parse().unwrap());
(result, values)
})
}
pub fn part_one(input: &str) -> Option<u64> {
let tests = parse(input);
let total = tests.fold(0, |acc, (result, mut values)| {
let mut totals = Vec::new();
totals.push(values.next().unwrap());
let mut current_totals = Vec::new();
for value in values {
core::mem::swap(&mut totals, &mut current_totals);
for x in current_totals.drain(..) {
let plus = x + value;
let mul = x * value;
if plus <= result {
totals.push(plus);
}
if mul <= result {
totals.push(mul);
}
}
if totals.is_empty() {
break;
}
}
if totals.iter().any(|&x| x == result) {
acc + result
} else {
acc
}
});
Some(total)
}
fn concat(lhs: u64, rhs: u64) -> u64 {
let pow_10 = rhs.ilog10();
lhs * 10_u64.pow(pow_10 + 1) + rhs
}
pub fn part_two(input: &str) -> Option<u64> {
let tests = parse(input);
let total = tests.fold(0, |acc, (result, mut values)| {
let mut totals = Vec::new();
totals.push(values.next().unwrap());
let mut current_totals = Vec::new();
for value in values {
core::mem::swap(&mut totals, &mut current_totals);
for x in current_totals.drain(..) {
let plus = x + value;
let mul = x * value;
let concat = concat(x, value);
if plus <= result {
totals.push(plus);
}
if mul <= result {
totals.push(mul);
}
if concat <= result {
totals.push(concat);
}
}
if totals.is_empty() {
break;
}
}
if totals.iter().any(|&x| x == result) {
acc + result
} else {
acc
}
});
Some(total)
}
#[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));
}
#[test]
fn test_concat() {
#![allow(clippy::inconsistent_digit_grouping)]
assert_eq!(concat(64, 132), 64_132);
assert_eq!(concat(72, 9), 72_9);
assert_eq!(concat(10001, 9757575), 10001_9757575);
}
}