Problem
Given a 2D rectangular matrix of boolean values, (google)
write a function which returns whether or not the matrix is the same when rotated 180 degrees.
Solution
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
bool IsRotateMatrixSame(bool* mat, int rows, int cols)
{
for(int i = 0; i < (rows + 1) / 2; ++i){
for(int j = 0; j < cols; ++j){
if(mat[i * cols + j] != mat[(rows - i - 1) * cols + cols - j - 1]){
return false;
}
}
}
return true;
}
void DisplayMatrix(bool* mat, int rows, int cols, string msg)
{
cout << msg << endl;
for(int i = 0; i < rows; ++i){
for(int j = 0; j < cols; ++j){
cout << mat[i * cols + j] << " ";
}
cout << endl;
}
}
void DislayEquality(bool isEqual, string msg)
{
std::cout << msg << " is ";
isEqual ?
(cout << "same as the rotated 180 matrix") :
(cout << "Not same as the rotated 180 matrix");
cout << endl << endl;
}
int main(int argc, char* argv[])
{
bool mat1[4][5] = {
{true, true, false, false, true},
{true, false, false, true, true},
{true, true, false, false, true},
{true, false, false, true, true}
};
DisplayMatrix((bool *)mat1, 4, 5, "matrix1");
DislayEquality(IsRotateMatrixSame((bool*)mat1, 4, 5), "matrix 1");
bool mat2[4][4] = {
{true, true, true, false},
{true, false, false, false},
{false, false, false, true},
{false, false, true, true}
};
DisplayMatrix((bool *)mat2, 4, 4, "matrix2");
DislayEquality(IsRotateMatrixSame((bool*)mat2, 4, 4), "matrix2");
bool mat3[5][4] = {
{true, true, false, false},
{true, false, false, false},
{true, false, false, true},
{false, false, false, true},
{false, false, true, true}
};
DisplayMatrix((bool *)mat3, 5, 4, "matrix3");
DislayEquality(IsRotateMatrixSame((bool*)mat3, 5, 4), "matrix3");
bool mat4[5][4] = {
{true, true, false, false},
{true, false, false, false},
{true, true, false, false},
{false, false, false, true},
{false, false, true, true}
};
DisplayMatrix((bool *)mat4, 5, 4, "matrix4");
DislayEquality(IsRotateMatrixSame((bool*)mat4, 5, 4), "matrix4");
return 0;
}
Output
matrix1
1 1 0 0 1
1 0 0 1 1
1 1 0 0 1
1 0 0 1 1
matrix 1 is same as the rotated 180 matrix
matrix2
1 1 1 0
1 0 0 0
0 0 0 1
0 0 1 1
matrix2 is Not same as the rotated 180 matrix
matrix3
1 1 0 0
1 0 0 0
1 0 0 1
0 0 0 1
0 0 1 1
matrix3 is same as the rotated 180 matrix
matrix4
1 1 0 0
1 0 0 0
1 1 0 0
0 0 0 1
0 0 1 1
matrix4 is Not same as the rotated 180 matrix
Press any key to continue . . .