Skip to content

Instantly share code, notes, and snippets.

@towc
Created January 15, 2019 12:31
Show Gist options
  • Save towc/3e98e9caa83bb4a7eed973075eae1da2 to your computer and use it in GitHub Desktop.
Save towc/3e98e9caa83bb4a7eed973075eae1da2 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <map>
#include <memory>
struct InputLine {
int min;
std::string text;
};
InputLine parseLine(std::string line) {
// 000000000011111111112222222222
// 012345678901234567890123456789
// [YYYY-MM-DD hh:mm] Guard #123 begins shift
std::string minStr = line.substr(15, 17); // mm
int min = std::stoi(minStr);
std::string text = line.substr(19); // Text
return InputLine{min, text};
}
class Guard {
public:
int id;
std::vector<std::pair<int, int>> times;
int mostMin;
int mostVal;
int minsAsleep;
Guard (int id): id(id), mostMin(0), mostVal(0), minsAsleep(0) { }
Guard () : id(-1) {}
void calcMins() {
for(int i = 0; i < 59; ++i) {
int sum = 0;
for(const std::pair<int, int>& time : this->times) {
if (i < time.second && i >= time.first) {
++sum;
}
}
if (sum > this->mostVal) {
this->mostMin = i;
this->mostVal = sum;
}
}
for(const std::pair<int, int>& time : this->times) {
this->minsAsleep += time.second - time.first;
}
}
int getScore() {
return this->id * this->mostMin;
}
};
int main() {
std::ifstream inputStream("aoc-input-4");
std::string line;
std::vector<std::string> lines;
while(std::getline(inputStream, line)) {
lines.push_back(line);
}
std::sort(lines.begin(), lines.end());
std::map<int, Guard> guardMap;
int lastId;
for(const std::string& line : lines) {
auto [min, text] = parseLine(line);
switch (text[0]) {
case 'G': {
// 0123456789
// Guard #123
int id = std::stoi(text.substr(7, text.find(" ", 7)));
lastId = id;
if (!guardMap.count(id)) {
guardMap.insert({ id, Guard(id) });
}
} break;
case 'f': {
guardMap[lastId].times.push_back({ min, 0 });
} break;
case 'w': {
guardMap[lastId].times.back().second = min;
} break;
}
}
std::vector<Guard> guards;
for(std::map<int, Guard>::iterator it = guardMap.begin(); it != guardMap.end(); it++) {
guards.push_back(it->second);
}
int mostMins = 0;
Guard mostMinsGuard;
int mostVal = 0;
Guard mostValGuard;
for(Guard& guard : guards) {
guard.calcMins();
if (guard.minsAsleep > mostMins) {
mostMins = guard.minsAsleep;
mostMinsGuard = guard;
}
if (guard.mostVal > mostVal) {
mostVal = guard.mostVal;
mostValGuard = guard;
}
}
std::cout << mostMinsGuard.getScore() << "\n"
<< mostValGuard.getScore() << "\n";
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment