-
Notifications
You must be signed in to change notification settings - Fork 0
/
01.rs
72 lines (63 loc) · 1.85 KB
/
01.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
use itertools::Itertools;
fn main() {
let input = include_str!("../../input/01.txt");
println!("Part 1: {}", run(input, 2));
println!("Part 2: {}", run(input, 3));
}
fn parse_expense(raw_expense: &str) -> Vec<i64> {
raw_expense
.split_whitespace()
.map(|line| line.trim().parse::<i64>().expect("parse error"))
.collect()
}
fn find_2020_multiple(expenses: Vec<i64>, depth: usize) -> i64 {
let goal = 2020;
if depth == 0 {
0
} else {
expenses
.into_iter()
.combinations(depth)
.filter(|combination| combination.iter().sum::<i64>() == goal)
.map(|combination| combination.iter().product::<i64>())
.next()
.unwrap()
}
}
fn run(input: &str, depth: usize) -> i64 {
let expenses = parse_expense(input);
find_2020_multiple(expenses, depth)
}
#[cfg(test)]
mod day_1_tests {
use super::*;
#[test]
fn test_parse_expense() {
let results = vec![1721, 979, 366, 299, 675, 1456];
assert!(parse_expense("1721\n979\n366\n299\n675\n1456") == results);
}
#[test]
fn test_find_2020_multiple() {
let input = vec![1721, 979, 366, 299, 675, 1456];
let result = find_2020_multiple(input, 2);
assert!(514_579 == result);
}
#[test]
fn test_find_2020_multple_depth() {
let input = vec![1721, 979, 366, 299, 675, 1456];
let result = find_2020_multiple(input, 3);
assert!(241_861_950 == result);
}
#[test]
fn test_part_1() {
let results = run(include_str!("../../input/01.txt"), 2);
println!("{results}");
assert!(results == 864_864);
}
#[test]
fn test_part_2() {
let results = run(include_str!("../../input/01.txt"), 3);
println!("{results}");
assert!(results == 281_473_080);
}
}