-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday9.cpp
83 lines (70 loc) · 2.12 KB
/
day9.cpp
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
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <deque>
#include <vector>
using namespace std;
int findInvalid(string filename, int preamble_length) {
ifstream sstream(filename);
deque<int> preamble;
for (string ss; getline(sstream, ss); ) {
auto num = stoi(ss);
if (preamble.size() == preamble_length) {
bool valid = false;
for (int i = 0; i < preamble_length; i++) {
for (int j = i+1; j < preamble_length; j++) {
if (num == preamble[i] + preamble[j]) {
valid = true;
break;
}
if (valid) break;
}
}
preamble.pop_front();
if (!valid) return num;
}
preamble.push_back(num);
}
return -1;
}
int findWeakness(string filename, int invalid_num) {
ifstream sstream(filename);
vector<int> numbers;
for (string ss; getline(sstream, ss); ) {
auto num = stoi(ss);
if (num < invalid_num) {
numbers.emplace_back(num);
} else {
break;
}
}
// now find the contiguous sums
bool sum_found = false;
int sum_length = 2;
int weakness = 0;
while (!sum_found) {
for (int i = 0; i < numbers.size() - (sum_length-1); ++i) {
int partial_sum = 0;
for (int j = 0; j < sum_length; ++j) {
partial_sum += numbers[i+j];
}
if (partial_sum == invalid_num) {
auto min_num = numbers[i];
auto max_num = numbers[i];
for (int j = 1; j < sum_length; ++j) {
min_num = min(numbers[i+j], min_num);
max_num = max(numbers[i+j], max_num);
}
return min_num + max_num;
}
}
sum_length++;
}
return -1;
}
int main() {
auto invalid_num = findInvalid("day9.txt", 25);
cout << "Invalid number = " << invalid_num << endl;
cout << "Weakness = " << findWeakness("day9.txt", invalid_num) << endl;
}