-
Notifications
You must be signed in to change notification settings - Fork 0
/
09.rs
68 lines (61 loc) · 1.5 KB
/
09.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
#![feature(test)]
use std::collections::VecDeque;
use itertools::Itertools;
#[derive(Debug)]
struct Input {
numbers: Vec<u64>,
n: usize,
}
fn setup(input: &str) -> Input {
let mut lines = input.lines().peekable();
let n = if lines.peek().unwrap().starts_with("# n=") {
lines
.next()
.unwrap()
.split('=')
.nth(1)
.unwrap()
.parse()
.unwrap()
} else {
25
};
let numbers = lines.map(|line| line.parse().unwrap()).collect();
Input { numbers, n }
}
fn part1(input: &Input) -> u64 {
input
.numbers
.iter()
.copied()
.enumerate()
.skip(input.n)
.find(|&(i, x)| {
!(i - input.n..i).any(|j| {
(i - input.n..i).any(|k| {
input.numbers[j] != input.numbers[k] && input.numbers[j] + input.numbers[k] == x
})
})
})
.unwrap()
.1
}
fn part2(input: &Input) -> u64 {
let target = part1(input);
let mut nums = VecDeque::new();
let mut inp = input.numbers.iter().copied();
let mut sum = 0;
while sum != target {
if sum < target {
let x = inp.next().unwrap();
nums.push_back(x);
sum += x;
} else {
let x = nums.pop_front().unwrap();
sum -= x;
}
}
let (min, max) = nums.into_iter().minmax().into_option().unwrap();
min + max
}
aoc::main!(2020, 9, ex: 1);