Advent of Code 2022 - 2nd attempt in c++
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
1.6 KiB

2 years ago
#include <iostream>
#include <vector>
#include <unordered_set>
2 years ago
#include <algorithm>
2 years ago
using namespace std;
typedef vector<vector<unsigned char>> Input;
Input parse()
{
Input items;
for (string line; getline(cin, line);) {
vector<unsigned char> bag;
for (unsigned char c : line) {
if (c >= 'a') c = c - 'a' + 1;
else if (c >= 'A') c = c - 'A' + 27;
bag.push_back(c);
}
items.push_back(bag);
}
return items;
}
template<class T>
unordered_set<T> intersect(unordered_set<T> &a, unordered_set<T> &b)
{
unordered_set<T> o;
2 years ago
copy_if(a.begin(), a.end(), inserter(o, o.end()), [&](T i){return b.count(i);});
2 years ago
return o;
}
unsigned p1(Input &items)
{
unsigned sum = 0;
for (auto i : items) {
unsigned len = i.size() / 2;
auto one = unordered_set<unsigned char>(i.begin(), i.begin() + len);
auto two = unordered_set<unsigned char>(i.begin() + len, i.begin() + len * 2);
for (auto x : intersect(one, two)) sum += x;
}
return sum;
}
unsigned p2(Input &items)
{
unsigned sum = 0;
for (auto i = items.begin(); i < items.end(); i += 3) {
auto one = unordered_set<unsigned char>(i[0].begin(), i[0].end());
auto two = unordered_set<unsigned char>(i[1].begin(), i[1].end());
auto thr = unordered_set<unsigned char>(i[2].begin(), i[2].end());
auto inter = intersect(one, two);
inter = intersect(inter, thr);
for (auto x : inter) sum += x;
}
return sum;
}
int main()
{
auto input = parse();
cout << p1(input) << endl;
cout << p2(input) << endl;
}