Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if matrix is circular

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(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]) {
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading