I’m trying to write a function which will check if matrix is circular or not.
A square matrix is circular if the elements of each of its works except the first are obtained by cyclically moving the previous row by one place to the right.
#include <iostream>
#include <deque>
bool CircularMatrix(std::deque < std::deque < double >> & a) {
int columns = a[0].size();
for (int i = 1; i < a.size(); i++)
if (a[i].size() != columns)
return false;
for (int i = 1; i < a.size(); i++) {
for (int j = 0; j < columns; j++) {
std::cout << "(" << i << "," << j << ")" << a[i][j] << " ";
if (j == 0) {
if (a[i][j] != a[i - 1][columns - 1]) return false;
} else {
if (a[i][j] != a[i - i][j - 1]) {
std::cout << "(" << i << "," << j << ")" << a[i][j] << " ";
return false;
}
}
}
std::cout << "\n";
}
return true;
}
int main() {
std::deque<std::deque<double>>a{
{1,2,3},
{3,1,2},
{2,3,1}};
std::cout << CircularMatrix(a);
return 0;
}
OUTPUT:
(1,0)3 (1,1)1 (1,2)2
(2,0)2 (2,1)3 (2,1)3 0
So, the last element of matrix is printed wrong. It should be (2,2)1 (and because of that result would be 1(true) instead of 0(false)). Could you explain me why it print’s wrong result and how to fix it?
>Solution :
Your error is here
if (a[i][j] != a[i - i][j - 1]) {
---------------------^
should be
if (a[i][j] != a[i - 1][j - 1]) {