summaryrefslogtreecommitdiff
path: root/2.c
blob: 0fcd9597c1c308d2249c1084e92a32c5bd4afabc (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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>


enum RPS {
	ROCK,
	PAPR,
	SCRS,
};


enum RPS
rps_beats(enum RPS rps)
{
	switch (rps) {
	case ROCK: return SCRS;
	case PAPR: return ROCK;
	case SCRS: return PAPR;
	}
	return -1;
}


enum RPS
rps_loses(enum RPS rps)
{
	switch (rps) {
	case ROCK: return PAPR;
	case PAPR: return SCRS;
	case SCRS: return ROCK;
	}
	return -1;
}


int
rps_pickscore(enum RPS rps)
{
	switch (rps) {
	case ROCK: return 1;
	case PAPR: return 2;
	case SCRS: return 3;
	}
	return 0;
}


int
rps_gamescore_b(enum RPS a, enum RPS b)
{
	if (b == a)
		return 3;
	if (rps_beats(b) == a)
		return 6;
	return 0;
}


int
main(int argc, char ** argv)
{
	int part = 1, i;
	char buf[BUFSIZ];
	int score = 0;

	while ((i = getopt(argc, argv, "p:")) != -1) {
		switch (i) {
		case 'p':
			part = atoi(optarg);
			break;

		default:
			return -1;
		}
	}

	while (fgets(buf, sizeof(buf), stdin)) {
		enum RPS a, b;

		if (strlen(buf) != 4)
			break;
		switch (buf[0]) {
		case 'A': a = ROCK; break;
		case 'B': a = PAPR; break;
		case 'C': a = SCRS; break;
		default:
			fprintf(stderr, "Unexpected input: %c (0x%2d)\n", buf[0], buf[0]);
			return -1;
		}
		switch (part) {
		case 1:
			switch (buf[2]) {
			case 'X': b = ROCK; break;
			case 'Y': b = PAPR; break;
			case 'Z': b = SCRS; break;
			default:
				fprintf(stderr, "Unexpected input: %c (0x%2d)\n", buf[2], buf[2]);
				return -1;
			}
			break;

		case 2:
			switch (buf[2]) {
			case 'X': b = rps_beats(a); break;
			case 'Y': b = a; break;
			case 'Z': b = rps_loses(a); break;
			default:
				fprintf(stderr, "Unexpected input: %c (0x%2d)\n", buf[2], buf[2]);
				return -1;
			}
			break;

		default:
			fprintf(stderr, "Unexpected puzzle part %d\n", part);
			return -1;
		}

		score += rps_pickscore(b) + rps_gamescore_b(a, b);
	}

	printf("Score: %d\n", score);

	return 0;
}