commit c84db215e871fcc62e5b464ba493f6575df19d80
parent c8d4c877cd92d2461176ffc8fd1498ab6fa3523e
Author: bsandro <email@bsandro.tech>
Date: Sat, 7 Dec 2024 17:23:09 +0200
Day 07 p2
Diffstat:
1 file changed, 29 insertions(+), 12 deletions(-)
diff --git a/day07/main.cpp b/day07/main.cpp
@@ -10,19 +10,19 @@
enum class Op {
sum,
- mul
+ mul,
+ con
};
//@todo make generic function using template
-void genVariations(std::vector<Op> &v, size_t len, std::vector<std::vector<Op>> &vs) {
+void genVariations(std::vector<Op> &v, const std::vector<Op> &ops, size_t len, std::vector<std::vector<Op>> &vs) {
if (v.size()==len) {
vs.push_back(v);
return;
}
- static const std::vector<Op> ops = {Op::sum, Op::mul};
for (Op o:ops) {
v.push_back(o);
- genVariations(v, len, vs);
+ genVariations(v, ops, len, vs);
v.pop_back();
}
}
@@ -31,7 +31,8 @@ class Equation {
public:
int64_t res;
std::vector<int64_t> numbers;
- std::vector<std::vector<Op>> ps; // operator permutations
+ std::vector<std::vector<Op>> ps1; // operator permutations for part 1
+ std::vector<std::vector<Op>> ps2; // operator permutations for part 1
Equation(std::string in) {
char tmp[256] = {0};
@@ -47,6 +48,12 @@ public:
for (size_t i=0; i<ops.size(); ++i) {
if (ops[i]==Op::mul) r *= numbers[i+1];
if (ops[i]==Op::sum) r += numbers[i+1];
+ if (ops[i]==Op::con) {
+ std::stringstream ss;
+ ss << r << numbers[i+1];
+ //r = std::stoi(ss.str());
+ ss >> r;
+ }
}
return r;
}
@@ -54,7 +61,11 @@ public:
private:
void populate() {
std::vector<Op> v;
- genVariations(v, numbers.size()-1, ps);
+ std::vector<Op> ops = {Op::sum, Op::mul};
+ genVariations(v, ops, numbers.size()-1, ps1);
+ v.clear();
+ ops.push_back(Op::con);
+ genVariations(v, ops, numbers.size()-1, ps2);
}
};
@@ -75,24 +86,30 @@ T read_file(const std::string &path) {
}
return buf;
}
-
+//@todo threads!
int64_t part1(Data &input [[ maybe_unused ]]) {
int64_t r = 0;
for (auto &e:input) {
- //std::printf("res:%ld\n", e.res);
- for (auto &v:e.ps) {
- //std::printf("\ncalc()=%ld\n", e.calc(v));
+ for (auto &v:e.ps1) {
if (e.res==e.calc(v)) {
r+=e.res;
break;
}
}
- //std::printf("-------------\n");
}
return r;
}
int64_t part2(Data &input [[ maybe_unused ]]) {
- return 0;
+ int64_t r = 0;
+ for (auto &e:input) {
+ for (auto &v:e.ps2) {
+ if (e.res==e.calc(v)) {
+ r+=e.res;
+ break;
+ }
+ }
+ }
+ return r;
}
int main(int argc, char **argv) {