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
|
#include <fstream>
#include <iostream>
#include <set>
#include <sstream>
#include <string>
#include <tuple>
#include <vector>
using namespace std;
vector<tuple<long, vector<long>>>
read_file(string_view filename)
{
fstream input{ filename };
vector<tuple<long, vector<long>>> data;
for ( string line; getline(input, line); ) {
auto pos = line.find(':');
stringstream str{ line.substr(pos + 1) };
data.emplace_back(stol(line.substr(0, pos)), vector<long>{ istream_iterator<long>{ str }, {} });
}
return data;
}
void
part1(const vector<tuple<long, vector<long>>>& data)
{
auto can_evaluated = [](long first, vector<long> values) -> bool {
set<long> candidates = { first };
while ( values.size() > 1 ) {
auto value = values.back();
values.pop_back();
set<long> new_candidates;
for ( const auto candidate: candidates ) {
if ( candidate % value == 0 ) {
new_candidates.insert(candidate / value);
}
if ( candidate >= value ) {
new_candidates.insert(candidate - value);
}
}
candidates = new_candidates;
}
return values.size() == 1 && candidates.contains(values.back());
};
long sum = 0;
for ( const auto& [first, values]: data ) {
if ( can_evaluated(first, values) ) {
sum += first;
}
}
cout << sum << endl;
}
void
part2(const vector<tuple<long, vector<long>>>& data)
{
auto can_evaluated = [](long first, vector<long> values) -> bool {
set<long> candidates = { first };
while ( values.size() > 1 ) {
auto value = values.back();
values.pop_back();
set<long> new_candidates;
for ( const auto candidate: candidates ) {
if ( candidate % value == 0 ) {
new_candidates.insert(candidate / value);
}
if ( candidate >= value ) {
new_candidates.insert(candidate - value);
}
if ( candidate > value ) {
auto value_str = to_string(value);
auto candidate_str = to_string(candidate);
if ( candidate_str.ends_with(value_str) ) {
candidate_str.erase(candidate_str.length() - value_str.length());
new_candidates.insert(stol(candidate_str));
}
}
}
candidates = new_candidates;
}
return values.size() == 1 && candidates.contains(values.back());
};
long sum = 0;
for ( const auto& [first, values]: data ) {
if ( can_evaluated(first, values) ) {
sum += first;
}
}
cout << sum << endl;
}
int
main()
{
auto data = read_file("data/day07.txt");
part1(data);
part2(data);
}
|