-
Notifications
You must be signed in to change notification settings - Fork 3
/
matrix.h
59 lines (49 loc) · 1.42 KB
/
matrix.h
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
#ifndef MATRIX_H
#define MATRIX_H
struct Entry {
int row;
int col;
bool pressed;
};
template <int R, int C>
class Matrix {
public:
Matrix() {
for (int r = 0; r < R; ++r) rows_[r] = 0;
}
// Calculate the difference between this matrix and a new matrix.
// Returns the number of different entries. This matrix is updated.
int Difference(const Matrix& new_matrix, int max_entries, Entry* entries) {
int num_entries = 0;
for (int r = 0; r < R && num_entries < max_entries; ++r) {
int diff = rows_[r] ^ new_matrix.rows_[r];
if (diff == 0) continue;
for (int c = 0; c < C && num_entries < max_entries; ++c) {
if (diff & (1<<c)) {
bool pressed = new_matrix.IsPressed(r, c);
entries[num_entries].row = r;
entries[num_entries].col = c;
entries[num_entries].pressed = pressed;
++num_entries;
// Keep up with the new matrix for the difference.
if (pressed) Press(r, c);
else Release(r, c);
}
}
}
return num_entries;
}
bool IsPressed(int row, int col) const {
return rows_[row] & (1<<col);
}
void Press(int row, int col) {
rows_[row] |= (1<<col);
}
void Release(int row, int col) {
rows_[row] &= ~(1<<col);
}
private:
// Bitmap indicating pressed keys in the matrix.
int rows_[R];
};
#endif