aoc

My solutions for the Advent of Code
git clone https://git.tronto.net/aoc
Download | Log | Files | Refs | README

day03a.cpp (896B)


      1 #include <algorithm>
      2 #include <iostream>
      3 #include <sstream>
      4 #include <string>
      5 #include <string_view>
      6 #include <vector>
      7 using namespace std;
      8 
      9 int trymult(const string_view &s) {
     10 	if (s.substr(0, 4) != "mul(")
     11 		return 0;
     12 
     13 	auto t = s.substr(4, s.length()-4);
     14 
     15 	int x = 0, y = 0;
     16 	int i = 0;
     17 	for (; i < 3; i++)
     18 		if (t[i] >= '0' && t[i] <= '9')
     19 			x = (x*10) + t[i]-'0';
     20 		else break;
     21 	if (i == 0 || t[i] != ',')
     22 		return 0;
     23 	i++;
     24 	int j = 0;
     25 	for (; j < 3; j++)
     26 		if (t[i+j] >= '0' && t[i+j] <= '9')
     27 			y = (y*10) + t[i+j]-'0';
     28 		else break;
     29 	if (j == 0 || t[j+i] != ')')
     30 		return 0;
     31 	return x*y;
     32 }
     33 
     34 int mults(const string &line) {
     35 	int result = 0;
     36 	for (auto i = line.begin(); i != line.end(); i++)
     37 		result += trymult(string_view(i, line.end()));
     38 	return result;
     39 }
     40 
     41 int main() {
     42 	string line;
     43 	int result = 0;
     44 	while (cin >> line)
     45 		result += mults(line);
     46 	cout << result << endl;
     47 	return 0;
     48 }