/
sb-read.cpp
103 lines (88 loc) · 2.49 KB
/
sb-read.cpp
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
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctype.h>
#include <iostream>
#include <vector>
using namespace std;
#define talloc(type, num) (type *) malloc(sizeof(type)*(num))
class Superball {
public:
Superball(int argc, char **argv);
int r;
int c;
int mss;
int empty;
vector <int> board;
vector <int> goals;
vector <int> colors;
};
void usage(const char *s)
{
fprintf(stderr, "usage: sb-read rows cols min-score-size colors\n");
if (s != NULL) fprintf(stderr, "%s\n", s);
exit(1);
}
Superball::Superball(int argc, char **argv)
{
int i, j;
string s;
if (argc != 5) usage(NULL);
if (sscanf(argv[1], "%d", &r) == 0 || r <= 0) usage("Bad rows");
if (sscanf(argv[2], "%d", &c) == 0 || c <= 0) usage("Bad cols");
if (sscanf(argv[3], "%d", &mss) == 0 || mss <= 0) usage("Bad min-score-size");
colors.resize(256, 0);
for (i = 0; i < strlen(argv[4]); i++) {
if (!isalpha(argv[4][i])) usage("Colors must be distinct letters");
if (!islower(argv[4][i])) usage("Colors must be lowercase letters");
if (colors[argv[4][i]] != 0) usage("Duplicate color");
colors[argv[4][i]] = 2+i;
colors[toupper(argv[4][i])] = 2+i;
}
board.resize(r*c);
goals.resize(r*c, 0);
empty = 0;
for (i = 0; i < r; i++) {
if (!(cin >> s)) {
fprintf(stderr, "Bad board: not enough rows on standard input\n");
exit(1);
}
if (s.size() != c) {
fprintf(stderr, "Bad board on row %d - wrong number of characters.\n", i);
exit(1);
}
for (j = 0; j < c; j++) {
if (s[j] != '*' && s[j] != '.' && colors[s[j]] == 0) {
fprintf(stderr, "Bad board row %d - bad character %c.\n", i, s[j]);
exit(1);
}
board[i*c+j] = s[j];
if (board[i*c+j] == '.') empty++;
if (board[i*c+j] == '*') empty++;
if (isupper(board[i*c+j]) || board[i*c+j] == '*') {
goals[i*c+j] = 1;
board[i*c+j] = tolower(board[i*c+j]);
}
}
}
}
main(int argc, char **argv)
{
Superball *s;
int i, j;
int ngoal, tgoal;
s = new Superball(argc, argv);
tgoal = 0;
ngoal = 0;
for (i = 0; i < s->r*s->c; i++) {
if (s->goals[i] && s->board[i] != '*') {
tgoal += s->colors[s->board[i]];
ngoal++;
}
}
printf("Empty cells: %2d\n", s->empty);
printf("Non-Empty cells: %2d\n", s->r*s->c - s->empty);
printf("Number of pieces in goal cells: %2d\n", ngoal);
printf("Sum of their values: %2d\n", tgoal);
exit(0);
}