-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchessboard.cpp
99 lines (89 loc) · 2.51 KB
/
chessboard.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
#include <iostream>
#include <stdexcept>
#include <iomanip>
using namespace std;
class ChessBoardArray {
protected:
class Row {
public:
Row(ChessBoardArray &a, int i): array(a), row(i) {}
int & operator [] (int i) const {
return array.select(row, i);
};
private:
int row;
ChessBoardArray &array;
};
class ConstRow {
public:
ConstRow(const ChessBoardArray &a, int i): array(a), row(i) {}
int operator [] (int i) const {
return array.select(row, i);
};
private:
const ChessBoardArray &array;
int row;
};
public:
ChessBoardArray(unsigned size = 0, unsigned base = 0) {
data = new int[(size*size + 1)/2];
sizea = size;
baseCBA = base;
};
ChessBoardArray(const ChessBoardArray &a) {
data = new int[(a.sizea*a.sizea + 1)/2];
sizea = a.sizea;
baseCBA = a.baseCBA;
for (unsigned i = 0; i < (sizea*sizea + 1)/2; i++) {
data[i] = a.data[i];
}
};
~ChessBoardArray() {
delete [] data;
};
ChessBoardArray & operator = (const ChessBoardArray &a) {
delete [] data;
sizea = a.sizea;
baseCBA = a.baseCBA;
data = new int[(sizea*sizea + 1)/2];
for (unsigned i = 0; i < (sizea*sizea + 1)/2; i++) {
data[i] = a.data[i];
}
return *this;
};
int & select (int i, int j) {
return data[loc(i, j)];
};
int select(int i, int j) const {
return data[loc(i, j)];
};
const Row operator [] (int i) {
return Row(*this, i);
};
const ConstRow operator [] (int i) const {
return ConstRow(*this, i);
};
friend ostream & operator << (ostream &out, const ChessBoardArray &a) {
for (int i = a.baseCBA; i < a.baseCBA + a.sizea; i++) {
for (int j = a.baseCBA; j < a.baseCBA + a.sizea; j++) {
out << setw(4);
if ((i + j - 2 * a.baseCBA) % 2 == 0) {
out << a.select(i, j);
}
else out << 0;
}
out << endl;
}
return out;
};
private:
unsigned int loc(int i, int j) const throw(out_of_range) {
int di = i - baseCBA, dj = j - baseCBA;
if (di < 0 || dj < 0 || di >= sizea || dj >= sizea || (i + j)%2 == 1) {
throw out_of_range("BROKEN ARROW");
}
return (di*sizea + dj)/2;
};
int *data;
unsigned sizea, baseCBA;
};