-
Notifications
You must be signed in to change notification settings - Fork 0
/
day-9.rs
77 lines (68 loc) · 1.71 KB
/
day-9.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
use aoc_2023::{aoc, str_block};
const INPUT: &str = include_str!("day-9.txt");
#[allow(dead_code)]
const INPUT_EX: &str = str_block! {"
0 3 6 9 12 15
1 3 6 10 15 21
10 13 16 21 30 45
"};
aoc! {
struct Day9 {
values: Vec<Vec<isize>>,
}
self(input = INPUT) {
Ok(Self {
values: input.lines().map(|line| line.split(' ')
.map(|n| n.parse().map_err(|_| "parse error"))
.collect()).collect::<Result<_, _>>()?,
})
}
1 part1 isize {
Ok(self.values.iter().map(find_sequence).sum())
}
2 part2 isize {
Ok(self.values.iter().map(find_sequence_2).sum())
}
INPUT_EX { 1 part1 = 114, 2 part2 = 2 }
INPUT { 1 part1 = 1938731307, 2 part2 = 948 }
}
#[allow(clippy::ptr_arg)]
fn find_sequence(seq: &Vec<isize>) -> isize {
let mut seq = seq.clone();
let mut sum = 0;
for len in (0..=seq.len()).rev() {
let mut all_zeroes = true;
for i in 0..len - 1 {
seq[i] = seq[i + 1] - seq[i];
if seq[i] != 0 {
all_zeroes = false;
}
}
sum += seq[len - 1];
if all_zeroes {
return sum;
}
}
unreachable!();
}
#[allow(clippy::ptr_arg)]
fn find_sequence_2(seq: &Vec<isize>) -> isize {
let mut seq = seq.clone();
let mut sum = 0;
let mut n = 1;
for start in 0.. {
let mut all_zeroes = true;
for i in (start..seq.len() - 1).rev() {
seq[i + 1] -= seq[i];
if seq[i + 1] != 0 {
all_zeroes = false;
}
}
sum += n * seq[start];
n = -n;
if all_zeroes {
return sum;
}
}
unreachable!();
}