aboutsummaryrefslogtreecommitdiff
path: root/2018/src/day02.cpp
blob: 5dc6c7fd0a1b9b2f23c0c6d49813e26144e5b6b4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <filesystem>
#include <fstream>
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <vector>

using namespace std;

namespace {

vector<string>
read_lines(const filesystem::path& filename)
{
	ifstream       file{ filename };
	vector<string> lines;

	for ( string line; getline(file, line); ) {
		lines.emplace_back(line);
	}

	return lines;
}

void
part1(const vector<string>& lines)
{
	int twos   = 0;
	int threes = 0;
	for ( const auto& line: lines ) {
		map<char, int> foo;
		for ( const auto chr: line ) {
			foo[chr]++;
		}

		set<int> counts;
		for ( const auto& [chr, count]: foo ) {
			counts.insert(count);
		}

		if ( counts.contains(2) ) {
			++twos;
		}
		if ( counts.contains(3) ) {
			++threes;
		}
	}
	cout << "Part 1: " << twos * threes << '\n';
}

void
part2(const vector<string>& lines)
{
	for ( size_t i = 0; i != lines.size(); ++i ) {
		for ( size_t j = i + 1; j != lines.size(); ++j ) {
			const auto& lhs = lines.at(i);
			const auto& rhs = lines.at(j);

			if ( lhs.length() != rhs.length() ) {
				throw runtime_error("invalid data");
			}

			string result;
			for ( size_t k = 0; k != lhs.length(); ++k ) {
				if ( lhs[k] == rhs[k] ) {
					result += lhs[k];
				}
			}

			if ( result.length() + 1 == lhs.length() ) {
				cout << "Part 2: " << result << '\n';
				return;
			}
		}
	}
}

} // namespace

int
main()
{
	auto lines = read_lines("data/day02.txt");
	part1(lines);
	part2(lines);
}