-
Notifications
You must be signed in to change notification settings - Fork 1
/
Matrix.cpp
93 lines (79 loc) · 2.04 KB
/
Matrix.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
#include <iostream>
#include <functional>
#include <cmath>
#include "Matrix.hpp"
Matrix::Matrix(int h, int w) {
srand(time(0));
this->h = h;
this->w = w;
this->read = new unsigned short *[h];
this->write = new unsigned short *[h];
for (int i = 0; i < h; i++) {
this->read[i] = new unsigned short[w];
this->write[i] = new unsigned short[w];
for (int j = 0; j < w; j++) {
this->read[i][j] = floor(rand() % 2);
this->write[i][j] = 0;
}
}
}
Matrix::~Matrix() {
for (int i = 0; i < this->h; i++) {
delete[] this->read[i];
delete[] this->write[i];
}
delete[] this->read;
delete[] this->write;
}
void Matrix::print() const{
// std::cout << "\n";
int h = this->h;
int w = this->w;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
std::cout << (this->read[i][j] ? "\u2588\u2588" : " ");
}
std::cout << std::endl;
}
std::cout << std::endl;
}
inline void Matrix::set(int i, int j, unsigned short v) {
this->write[mod(i, this->h)][mod(j, this->w)] = v;
}
inline unsigned short Matrix::get(int i, int j) const {
return this->read[mod(i,this->h)][mod(j,this->w)];
}
void Matrix::forEach(std::function<unsigned short(int, int, unsigned short, int)>f) {
forEach(0, this->h, f);
}
void Matrix::forEach(int start,
int end,
std::function<unsigned short(int, int, unsigned short, int)>f) {
for (int i = start; i < end; i++) {
for (int j = 0; j < this->w; j++) {
unsigned short r = f(i, j, this->read[i][j], countAlive(i, j));
if (r!=-1) {
set(i,j,r);
}
}
}
}
void Matrix::swap() {
this->tmp = this->read;
this->read = this->write;
this->write = tmp;
}
int Matrix::countAlive(int x, int y) const{
int count = 0;
for (int i = x - 1; i <= x + 1; i++) {
for (int j = y - 1; j <= y + 1; j++) {
if (((i != x) || (j != y)) && (get(i, j) == 1)) {
count++;
}
}
}
return count;
}
inline unsigned short Matrix::mod(int a, int b) const{
return (a % b + b) % b;
}