aboutsummaryrefslogtreecommitdiff
path: root/2016/src/day02.cpp
blob: 612de2880ddb681f06b98210800d2ca1f5d5547d (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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <tuple>
#include <vector>

using namespace std;

vector<string>
read_file(string_view filename)
{
	fstream        input{ filename };
	vector<string> lines;

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

void
part1(const vector<string>& lines)
{
	int pos_x = 1;
	int pos_y = 1;

	for ( const auto& line: lines ) {
		for ( const auto chr: line ) {
			switch ( chr ) {
			case 'U':
				--pos_y;
				break;
			case 'R':
				++pos_x;
				break;
			case 'L':
				--pos_x;
				break;
			case 'D':
				++pos_y;
				break;
			default:
				cerr << "unknown char: " << chr << endl;
				return;
			}

			pos_x = clamp(pos_x, 0, 2);
			pos_y = clamp(pos_y, 0, 2);
		}
		cout << pos_y * 3 + pos_x + 1;
	}
	cout << endl;
}

void
part2(const vector<string>& lines)
{
	const map<tuple<int, int>, char> keypad = {
		{ { 2, 0 }, '1' },
		{ { 1, 1 }, '2' },
		{ { 2, 1 }, '3' },
		{ { 3, 1 }, '4' },
		{ { 0, 2 }, '5' },
		{ { 1, 2 }, '6' },
		{ { 2, 2 }, '7' },
		{ { 3, 2 }, '8' },
		{ { 4, 2 }, '9' },
		{ { 1, 3 }, 'A' },
		{ { 2, 3 }, 'B' },
		{ { 3, 3 }, 'C' },
		{ { 2, 4 }, 'D' }
	};

	tuple<int, int> pos = { 0, 2 };

	for ( const auto& line: lines ) {
		for ( const auto chr: line ) {
			auto pos2 = pos;
			switch ( chr ) {
			case 'U':
				--get<1>(pos2);
				break;
			case 'R':
				++get<0>(pos2);
				break;
			case 'L':
				--get<0>(pos2);
				break;
			case 'D':
				++get<1>(pos2);
				break;
			default:
				cerr << "unknown char: " << chr << endl;
				return;
			}

			if ( keypad.contains(pos2) ) {
				pos = pos2;
			}
		}
		cout << keypad.at(pos);
	}
	cout << endl;
}

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