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
|
# include <iostream>
static constexpr int MAX_SIZE = 4;
// Just made up this defn.
int convert_char_to_color(char c) {
switch (c) { case 'X': return 1; case 'O': return 2; default: return 0; };
}
bool read_board_from_string(int board[MAX_SIZE][MAX_SIZE],
std::string board_string[MAX_SIZE],
int size) {
for (int row = 0; row < size; row++) {
std::string line = board_string[row];
for (int col = 0; col < size; col++) {
board[row][col] = convert_char_to_color(line[col]);
}
}
return true;
}
bool rows_are_same(const int board[MAX_SIZE][MAX_SIZE],
int const r1, int const r2) {
for (int i = 0; i < MAX_SIZE; ++i)
if (board[r1][i] != board[r2][i]) return false;
return true;
}
bool cols_are_same(const int board[MAX_SIZE][MAX_SIZE],
int const c1, int const c2) {
for (int i = 0; i < MAX_SIZE; ++i)
if (board[i][c1] != board[i][c2]) return false;
return true;
}
// both of these functions are almost identical.
// Duplicate code is bad! Is there a way to get rid of it?
// no size parameter needed in this case
bool board_has_no_duplicates(const int board[MAX_SIZE][MAX_SIZE]) {
for (int i = 1; i <= MAX_SIZE; ++i) {
for (int j = 1; j <= MAX_SIZE; ++j) {
if (i == j) continue;
if (cols_are_same(board, i, j) || rows_are_same(board, i, j))
return false;
}
}
return true;
}
void test_board_has_no_duplicates() {
int board[MAX_SIZE][MAX_SIZE];
/// FIXME: This board has duplicate rows.
std::string test_board_1[] = { "X-X-",
"XOX-",
"O-O-",
"O-O-" };
std::string test_board_2[] = { "OXXO",
"XOOX",
"OOXX",
"XXOO" };
int size_1 = 4;
read_board_from_string(board, test_board_1, size_1);
std::cout << board_has_no_duplicates(board) <<
" should be 0 -- there are duplicate rows in the test case." << std::endl;
read_board_from_string(board, test_board_2, size_1);
std::cout << board_has_no_duplicates(board) <<
" should be 0" << std::endl;
// You can use the assert() macro from the <cassert> header to do these sorts of tests less painfully.
// e.g.: assert(! board_has_no_duplicates(board)); // assertion should always be true.
}
int main() {
test_board_has_no_duplicates();
}
| |