Day two, and only starting it a half hour late. I feel so behind and it's only Day 2. I'm sure I can catch up and this was just an anomoly.
This one looks werid... but mostly odd string manipulation. I feel like having a hard-coded number of initial cubes makes hard-coding this a bit loaded, but it seems like a good way to start it all. In fact, I think I can hard code a lot of this.
I'm borrowing from a string splitting function I used a lot last year. (Side note: I really need to figure out how to put some of these helper functions I use a lot into their own file. It's not as easy to include other files in C++ as it is in other languages)
vector<string> split(string s, string delim)
{
vector<string> output;
while (s.find(delim) != string::npos)
{
size_t pos = s.find(delim);
output.push_back(s.substr(0, pos));
s.erase(0, pos + delim.length());
}
output.push_back(s);
return output;
}
Add that to split everything out, using ;
for rounds and ,
for individual pulls, and just checking each substring (eg. 20 red
) for the presence of the color string (red
) and just using that to compare;
auto baseSplit = split(line, ": ");
int gameNum = stoi(baseSplit[0].substr(5));
bool valid = true;
auto rounds = split(baseSplit[1], "; ");
for (string round: rounds)
{
auto pulls = split(round, ", ");
for (string pull: pulls)
{
auto parts = split(pull, " ");
if (parts[1] == "red" && stoi(parts[0]) > MAX_RED) valid = false;
else if (parts[1] == "green" && stoi(parts[0]) > MAX_GREEN) valid = false;
else if (parts[1] == "blue" && stoi(parts[0]) > MAX_BLUE) valid = false;
if (!valid) break;
}
if (!valid) break;
}
That worked pretty easily!
Part 2 doesn't seem too bad. Figure out, for each game, what the smallest number of cubes that could have produced that result. In essence - for each of the colors, what was the largest pull?
if (parts[1] == "red") red = max( red, stoi(parts[0]));
else if (parts[1] == "green") green = max(green, stoi(parts[0]));
else if (parts[1] == "blue") blue = max( blue, stoi(parts[0]));
A small change, plus multiplying the results, and it's all good!