This one looks interesting, if not overly complicated. I could probably do a 2d map for this one, one for the pairing of elements as described. Then, construct a new string with the elements provided in the example to make the polymers.
I realize that the last paragraph is probably nonsense without context, but well, the problem should be linked to in the title of each post. Hopefully that can make sense to anyone that stumbles across this without the context of the original puzzles?
That would assume that the AoC website is still around though. I don't have much interest in re-hosting things.
You can tell I am overthinking things when I'm worried about this blog post rather than the problem at hand.
string polymer;
map<char, map<char, char>> rules;
input >> polymer;
while (!input.eof()) {
string pair, addition;
input >> pair;
input >> line; // Toss arrow
input >> addition;
rules[pair[0]][pair[1]] = addition[0];
}
for (int i = 1; i <= ITERATIONS; i++) {
stringstream newPolymer;
for (int j = 0; j < polymer.size()-1; j++) {
newPolymer << polymer[j];
if (rules[polymer[j]][polymer[j+1]])
newPolymer << rules[polymer[j]][polymer[j+1]];
}
newPolymer << polymer[polymer.size()-1];
polymer = newPolymer.str();
}
This seems not too bad. Almost too easy? The first part seems like a complete problem already, not a partial problem, so I'm worried that the second part might be a bit more tricky...
Oh god, I knew it was too easy, it's a brute forcing problem. I have to go for four times as long, for something growing very exponentially.
I'm going to have to nearly completely rearchitect my solution.
I learned nothing from the lanternfish.
~
Once I figured out the trick with the rules, I realized it was almost exactly the same problem as the lanternfish. Basically, a rule was basically a mapping of inputs to outputs. For example, the rule AB -> C
simply results in two new pairs, AC
and CB
. Which just means making buckets for the pairs, then for the entire bucket AB
, I add that count to both AC
and CB
for the next iteration. Exactly like I did for the lanternfish.
The solution looks very different, but nonetheless works nearly instantly.
map<string, unsigned long long> polymer;
map<string, pair<string, string>> rules;
input >> line;
for (int i = 0; i < line.size()-1; i++)
polymer[line.substr(i, 2)]++;
char lastElem = line[line.size()-1];
while (!input.eof()) {
string in, addition, out1, out2;
input >> in;
input >> line; // Toss arrow
input >> addition;
out1 = in[0] + addition;
out2 = addition + in[1];
rules[in] = pair<string, string>(out1, out2);
}
for (int i = 1; i <= ITERATIONS; i++) {
map<string, unsigned long long> newPolymer;
for (auto pairs: polymer) {
pair<string, string> rule = rules[pairs.first];
newPolymer[rule.first] += pairs.second;
newPolymer[rule.second] += pairs.second;
}
polymer = newPolymer;;
}
It's weird feeling the despair of being stumped by a problem, then solving it so quickly...