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
|
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
#define ROWS 5
#define COLS 6
//forward functions declarations
void getCharMat(char mat[][COLS]);
void printCharMat(char mat[][COLS]);
bool isIn(char mat[][COLS],int i,int j);
int numOfNeighbours(char mat[][COLS],int i,int j);
void Game(char mat[][COLS]);
int main(int argc, char** argv) {//main function
char mat[ROWS][COLS];
//section 1 functions call
getCharMat(mat);
printCharMat(mat);
Game(mat);
printCharMat(mat);
return 0;
}
//section 1
void getCharMat(char mat[][COLS]){//getting matrix of *-.
srand((unsigned)time(0));
for(int i=0;i<ROWS;i++){//getting matrix of values 0-1
for(int j=0;j<COLS;j++)
mat[i][j]=rand()%2;
}
for(int i=0;i<ROWS;i++){//filling matrix of *-.
for(int j=0;j<COLS;j++){
if(mat[i][j]==0)
mat[i][j]='*';
else mat[i][j]='.';
}}
}
void printCharMat(char mat[][COLS]){//printing the matrix
for(int i=0;i<ROWS;i++){
for(int j=0;j<COLS;j++)
cout<<mat[i][j];
cout<<endl;
}
}
bool isIn(char mat[][COLS],int i,int j){//checking index in matrix
if(i>=0 && i<ROWS && j>=0 && j<COLS)
return true;
return false;
}
int numOfNeighbours(char mat[][COLS],int i,int j){
int count =0;
for(int k=i-1;k<=i+1;k++){//starting from index before chosen one to after
for(int m=j-1;m<=j+1;m++){//""""""""""""""""""""""""
if(k==i &&m==j ||(!isIn(mat,k,m)))continue;//skipping the chosen index and if index out of matrix
else if(mat[k][m]=='*')
count+=1;//counting stars in variable
}}
return count;
}
void Game(char mat[][COLS]){//applying the game on the matrix (replacing stars by numbers of it))
for(int i=0;i<ROWS;i++){
for(int j=0;j<COLS;j++)
if(mat[i][j]=='.')
mat[i][j]=static_cast<int>(numOfNeighbours(mat,i,j));//replacing stars with numbers in matrix
}
}
| |