How to check if two arrays are mirror images of each other in C?

Viewed 1956

I am trying to see how to use C to check if two 2d arrays are symmetrical/mirror to each other.

So for example, if

array1 = { { 2, 5, 10 }, { 2, 1, 9 } };
array2 = { { 10, 5, 2 }, { 9, 1, 2 } };

The arrays are really 2d arrays.

How should I approach this? So far I tried to read both 2d arrays and use if/else statements and a bool to check if both arrays are equal to each other or not. But I'm not sure how to check if they are mirror matrices of each other or not.

2 5 10  |  10 5 2
2 1  9  |   9 1 2

The compiler is from 89.

3 Answers

You wanted to read values to both matrices the same way (hint 1: use functions). So they will both look like this:

First one:

{{m1[0][0], m1[0][1], m1[0][2],..., m1[0][99]},
 {m1[1][0], m1[1][1], m1[1][2],..., m1[1][99]},
 ...
 {m1[99][0], m1[99][1], ..., m1[99][99]}}

second one:

{{m2[0][0], m2[0][1], m2[0][2],..., m2[0][99]},
 {m2[1][0], m2[1][1], m2[1][2],..., m2[1][100]},
 ...
 {m2[99][0], m2[99][1], ..., m2[99][99]}}

But you have an error in first loop of reading m1 array:

for (a = 0; b < row; i++)

And then inside your comparison loop, you have :

m1[row][col] != m2[row][col]

Which compares values of both matrices with the same indices. So instead of comparing m1[0][0] with m2[0][99] you are comparing m1[0][0] with m2[0][0].

Simple and short:

#include <stdio.h>
#define size 3

int main (void){
    int i,j,k,flag=1;
    int array1[][size] = { { 2, 5, 10},{ 2, 1, 9 } }, array2[][size] = { {10, 5, 2 }, { 9, 1, 2 } };

    //Check mirror image or not
    for(i=0;i<size-1;i++) {
        for(j=0,k=size-1;j<size;j++,k--) {
            if(array1[i][j]!=array2[i][k]) {
                flag=0;
                break;
            }
        }
    }
    if(flag)
        printf("Mirror image to each other");
    else
        printf("Not a mirror image to each other");
    return 0;
}

You can verify this property with 2 nested loops:

#include <stdio.h>

#define COLS 3
#define ROWS 2

int main(void) {
    int array1[ROWS][COLS] = { { 2, 5, 10 }, { 2, 1, 9 } };
    int array2[ROWS][COLS] = { { 10, 5, 2 }, { 9, 1, 2 } };
    int xmirror = 1;
    int ymirror = 1;
    int xymirror = 1;

    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLS; j++) {
            if (array1[i][j] != array2[i][COLS - 1 - j])
                xmirror = 0;
            if (array1[i][j] != array2[ROWS - 1 - i][j])
                ymirror = 0;
            if (array1[i][j] != array2[ROWS - 1 - i][COLS - 1 - j])
                xymirror = 0;
        }
    }
    if (xymirror)
        printf("Mirror image to each other rowwise and columnwise\n");
    if (ymirror)
        printf("Mirror image to each other rowwise\n");
    if (xmirror)
        printf("Mirror image to each other columnwise\n");
    if (xmirror + ymirror + xymirror == 0)
        printf("Not a mirror image of each other\n");
    return 0;
}
Related