#include <stdio.h>
#include <string.h>
#include <stdbool.h>
/* VARIANT 0: compare elements of arrays in a nested loop
-> no obvious advantages over VARIANT 1 */
bool matrix_equal0(
const int *a, const int *b, unsigned int rows, unsigned int columns)
{
for (unsigned int i = 0; i < rows; i++) {
for (unsigned int j = 0; j < columns; j++) {
if (a[i * columns + j] != b[i * columns + j]) {
return false;
}
}
}
return true;
}
/* VARIANT 1: compare elements of matrices one by one,
simpler and more performant than VARIANT 0 */
bool matrix_equal1(
const int *a, const int *b, unsigned int rows, unsigned int columns)
{
unsigned int i = rows * columns;
while (i--) {
if (*a++ != *b++) {
return false;
}
}
return true;
}
/* VARIANT 2:
compare both arrays as a chunk of memory (possible but not recommended) */
bool matrix_equal2(
const int *a, const int *b, unsigned int rows, unsigned int columns)
{
return (memcmp(a, b, rows * columns * sizeof(int)) == 0);
}
int main(void)
{
const int mat0[3][3] = {
{ 1, 2, 3, },
{ 4, 5, 6, },
{ 7, 8, 9, },
};
const int mat1[3][3] = {
{ 1, 2, 3, },
{ 4, 5, 6, },
{ 7, 8, 9, },
};
const int mat2[3][3] = {
{ 1, 2, 3, },
{ 4, 5, 6, },
{ 7, 8, 9999, },
};
if (matrix_equal0(&mat0[0][0], &mat1[0][0], 3, 3)) {
printf("VARIANT 0: mat0 and mat1 are equal!\n");
}
if (matrix_equal0(&mat0[0][0], &mat2[0][0], 3, 3) == false) {
printf("VARIANT 0: mat0 and mat2 are NOT equal!\n");
}
if (matrix_equal1(&mat0[0][0], &mat1[0][0], 3, 3)) {
printf("VARIANT 1: mat0 and mat1 are equal!\n");
}
if (matrix_equal1(&mat0[0][0], &mat2[0][0], 3, 3) == false) {
printf("VARIANT 1: mat0 and mat2 are NOT equal!\n");
}
if (matrix_equal2(&mat0[0][0], &mat1[0][0], 3, 3)) {
printf("VARIANT 2: mat0 and mat1 are equal!\n");
}
if (matrix_equal2(&mat0[0][0], &mat2[0][0], 3, 3) == false) {
printf("VARIANT 2: mat0 and mat2 are NOT equal!\n");
}
return 0;
}