-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathday_07b.cpp
85 lines (81 loc) · 2.61 KB
/
day_07b.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
84
85
#include <algorithm>
#include <cmath>
#include <fstream>
#include <iostream>
#include <ranges>
#include <string>
#include <vector>
template<long long base>
bool incrementNumberWithBase(std::vector<long long>& num ) {
long long carry = 1;
for (auto& ele : std::views::reverse(num)) {
if (carry == 1) {
ele += 1;
if (ele == base) {
carry = 1;
ele = 0;
} else {
carry = 0;
}
}
}
return (carry != 1);
// If this is 1 then exceeded the length of the vector
// If the vector passed in has a size == the number of operators between digits, then no longer need to increment
}
bool solve(const std::vector<long long>& equation) {
if (equation.size() == 2) {
return equation[0] == equation[1];
}
auto operators = std::vector<long long>(equation.size() - 2, 0);
do {
long long ans = equation[1];
for (const auto [idx, ele] : std::views::enumerate(operators)) {
if (ele == 0) {
ans += equation[idx + 2];
} else if (ele == 1) {
ans *= equation[idx + 2];
} else {
int n_digits = 0;
auto temp = equation[idx + 2];
while(temp > 0) {
n_digits++;
temp /= 10;
}
ans = ans * std::pow(10, n_digits) + equation[idx + 2];
}
}
if (ans == equation[0]) return true;
} while (incrementNumberWithBase<3>(operators));
return false;
}
int main(int argc, char* argv[]) {
std::string input = "../input/day_07_input";
if (argc > 1) {
input = argv[1];
}
std::ifstream file(input);
std::string line;
std::vector<std::vector<long long>> equations;
long long ans = 0;
static constexpr std::string digits = "0123456789";
while(std::getline(file, line)) {
equations.emplace_back();
auto& equation = equations.back();
std::size_t current = 0;
std::size_t end_idx = line.find_first_not_of(digits, current);
while(end_idx != std::string::npos) {
equation.push_back(std::stoll(line.substr(current, end_idx - current)));
current = line.find_first_of(digits, end_idx);
end_idx = line.find_first_not_of(digits, current);
}
equation.push_back(std::stoll(line.substr(current, line.size() - current)));
}
for (const auto equation : equations) {
if(solve(equation)) {
ans += equation[0];
}
}
std::cout << ans << '\n';
return 0;
}