Skip to content

Instantly share code, notes, and snippets.

@maudzekod4000
Created December 13, 2024 20:28
Show Gist options
  • Save maudzekod4000/66fbbcfb85c17b9a1fdb2fd77fb1dc98 to your computer and use it in GitHub Desktop.
Save maudzekod4000/66fbbcfb85c17b9a1fdb2fd77fb1dc98 to your computer and use it in GitHub Desktop.
AOC2024-Problem 3 Part 2
#include <iostream>
#include <fstream>
#include <string>
#include <ctype.h>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <sstream>
#include <regex>
using namespace std;
enum class TokenType {
DO,
DONT,
MUL
};
struct Token {
TokenType type;
int x, y;
};
struct Scanner {
Scanner(std::string code) : code(code) {}
std::vector<Token> scan() {
while (!empty()) {
char c = current();
switch (c)
{
case 'd':
advance();
if (match('o')) {
if (match('(')) {
if (match(')')) {
tokens.push_back({ TokenType::DO, 0, 0 });
}
}
else if (match('n')) {
if (match('\'')) {
if (match('t')) {
if (match('(')) {
if (match(')')) {
tokens.push_back({ TokenType::DONT, 0, 0 });
}
}
}
}
}
}
break;
case 'm':
advance();
consumeMul();
break;
default:
advance();
break;
}
}
return tokens;
}
private:
std::string code;
int idx = 0;
std::vector<Token> tokens; // result
void consumeMul() {
if (!match('u')) {
return;
}
if (!match('l')) {
return;
}
if (!match('(')) {
return;
}
if (!isDigit()) {
return;
}
int x = consumeNumber();
if (!match(',')) {
return;
}
if (!isDigit()) {
return;
}
int y = consumeNumber();
if (!match(')')) {
return;
}
tokens.push_back({ TokenType::MUL, x, y });
}
int consumeNumber() {
int currIdx = idx;
while (isDigit()) {
advance();
}
std::string s = code.substr(currIdx, idx - currIdx);
return std::stoi(s);
}
bool isDigit() {
return !empty() && std::isdigit(current());
}
void advance() {
idx++;
}
bool match(char c) {
if (empty()) {
return false;
}
if (c == code[idx]) {
advance();
return true;
}
return false;
}
bool empty() {
return idx >= code.size();
}
char current() {
return code[idx];
}
};
int main()
{
ifstream infile("input.txt");
if (!infile.is_open()) {
cout << "File prob\n";
return -1;
}
long long total = 0;
string line;
TokenType state = TokenType::DO;
while (infile.good()) {
getline(infile, line);
if (line.empty()) continue;
Scanner scanner(line);
auto tokens = scanner.scan();
for (auto token : tokens) {
if (token.type == TokenType::DO) {
state = token.type;
}
else if (token.type == TokenType::DONT) {
state = token.type;
}
else {
if (state == TokenType::DO) {
total += token.x * token.y;
}
}
}
}
infile.close();
std::cout << total << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment