Skip to content

Instantly share code, notes, and snippets.

@pancanin
Created December 12, 2023 22:24
Show Gist options
  • Save pancanin/66f7a9130a86e5b3255c820c4bbf8060 to your computer and use it in GitHub Desktop.
Save pancanin/66f7a9130a86e5b3255c820c4bbf8060 to your computer and use it in GitHub Desktop.
Advent of Code - Day 2
#include <iostream>
#include <fstream>
#include <string>
#include <ctype.h>
#include <vector>
#include <sstream>
using namespace std;
struct Game {
int r, g, b;
};
// for string delimiter
std::vector<std::string> split(std::string s, std::string delimiter) {
size_t pos_start = 0, pos_end, delim_len = delimiter.length();
std::string token;
std::vector<std::string> res;
while ((pos_end = s.find(delimiter, pos_start)) != std::string::npos) {
token = s.substr(pos_start, pos_end - pos_start);
pos_start = pos_end + delim_len;
res.push_back(token);
}
res.push_back(s.substr(pos_start));
return res;
}
// returns vector of game sets for each game string, i.e.
// from "Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green"
// it should return 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
vector<Game> parseGameSets(string str) {
string setsStr = str.substr(str.find(":") + 1);
vector<string> sets = split(setsStr, ";");
vector<Game> gameSets;
for (auto& s : sets) {
vector<string> cubes = split(s, ",");
Game gameSetObj{};
for (auto& c : cubes) {
stringstream strS(c);
int count = 0;
string type;
strS >> count >> type;
if (type == "red") {
gameSetObj.r += count;
}
else if (type == "green") {
gameSetObj.g += count;
}
else if (type == "blue") {
gameSetObj.b += count;
}
}
gameSets.push_back(gameSetObj);
}
return gameSets;
}
int main()
{
ifstream infile("input.txt");
if (!infile.is_open()) {
cout << "File prob\n";
return -1;
}
string line;
unsigned long long sum = 0;
int id = 1;
while (infile.good()) {
getline(infile, line);
vector<Game> games = parseGameSets(line);
int r, g, b;
r = g = b = 0;
for (auto& game : games) {
r = max(r, game.r);
g = max(g, game.g);
b = max(b, game.b);
}
sum += r * g * b;
id++;
}
cout << "Sum " << sum << "\n";
infile.close();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment