aboutsummaryrefslogtreecommitdiff
path: root/2021/day14/day14.cpp
blob: 63656b66d50debc8193add717abbd3f7ea0e4e98 (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 <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <map>
#include "../utils.h"

std::map<std::string, long> apply (std::map<std::string, long> pairs, 
	std::map<std::string, char> rules, std::map<char, long> &count) 
{
	std::map<std::string, long> next = pairs;
	for (auto &pair : pairs) {
		char c = rules[pair.first];
		count[c] += pair.second;
		std::string l; 
		l.push_back(pair.first[0]);
		l.push_back(c);
		std::string r; 
		r.push_back(c);
		r.push_back(pair.first[1]);
		next[pair.first] -= pair.second;
		next[l] += pair.second;
		next[r] += pair.second;
	}
	return next;
}

void to_pairs (std::string init, std::map<std::string, long> &pairs) {
	for (std::size_t i=0; i<init.size()-1; i++) {
		std::string seg = init.substr(i, 2);
		pairs[seg] ++;
	}
}

long tally (std::map<char, long> map) {
	std::vector<long> f;
	for (auto p : map) {
	       	f.push_back(p.second);
		std::cout << p.first << " " << p.second << std::endl;	
	}
	std::sort(f.begin(), f.end());
	return f[f.size()-1] - f[0];
}

int main (int argc, char *argv[]) {
	std::string raw;
	std::getline(std::ifstream(argv[1]), raw, '\0');
	std::vector<std::string> parts, strrules;
	split(parts, raw, "\n\n");
	split(strrules, parts[1], "\n");

	std::string polymer = parts[0];
	std::cout << "starting polymer: " << polymer << std::endl;

	std::map<std::string, long> pairs;
	std::map<std::string, char> rules;
	for (auto strrule : strrules) {
		if (strrule.size() == 0) continue;
		std::vector<std::string> rl;
		split(rl, strrule, " -> ");
		rules[rl[0]] = rl[1][0];
		pairs[rl[0]] = 0;
	}

	to_pairs(polymer, pairs);
	
	std::map<char, long> count;
	for (auto pair : pairs) {
		count[pair.first[0]] = 0;
		count[pair.first[1]] = 0;
	}

	for (char c : polymer) {
		count[c] ++;
	}

	long iter = 10;
	if (argc > 2) iter = atoi(argv[2]);
	for (long i=0; i<iter; i++) {
		pairs = apply(pairs, rules, count);
	}

	long res = tally(count);
	std::cout << "most common - least common: " << res << std::endl;

	return 0;
}