Created
December 17, 2024 13:06
-
-
Save juanfal/3f12f58909ef036c47425fb734ddfa79 to your computer and use it in GitHub Desktop.
isMagic
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 2.isMagic.cpp | |
// juanfc 2024-12-16 | |
// | |
#include <iostream> | |
#include <array> | |
using namespace std; | |
const int N = 3; | |
typedef array<array<int,N>,N> TSqMat; | |
int main() | |
{ | |
void test(TSqMat); | |
TSqMat a = {{ | |
{{2, 7, 6}}, | |
{{9, 5, 1}}, | |
{{4, 3, 8}} | |
}}; | |
TSqMat b = {{ | |
{{2, 2, 6}}, | |
{{9, 5, 1}}, | |
{{4, 3, 8}} | |
}}; | |
TSqMat c = {{ | |
{{2, 2, 2}}, | |
{{2, 2, 2}}, | |
{{2, 2, 2}} | |
}}; | |
test(a); | |
test(b); | |
test(c); | |
return 0; | |
} | |
void test(TSqMat m) | |
{ | |
void print(TSqMat); | |
bool isMagic(TSqMat); | |
if (isMagic(m)) | |
cout << "Is magic" << endl; | |
else | |
cout << "Is Not magic" << endl; | |
} | |
bool isMagic(TSqMat m) | |
{ | |
void print(TSqMat); | |
bool noRepetitions(TSqMat); | |
int sumRow(TSqMat, int); | |
int sumCol(TSqMat, int); | |
int sumDiag(TSqMat); | |
int sumAntiDiag(TSqMat); | |
print(m); | |
bool ok = noRepetitions(m); | |
int magicV = sumRow(m, 0); | |
int i = 1; | |
while (i < N and ok) { | |
ok = sumRow(m, i) == magicV; | |
++i; | |
} | |
i = 0; | |
while (i < N and ok) { | |
ok = sumCol(m, i) == magicV; | |
++i; | |
} | |
return ok and sumDiag(m) == magicV and sumAntiDiag(m) == magicV; | |
} | |
void print(TSqMat m) | |
{ | |
for (int row = 0; row < N; ++row) { | |
for (int col = 0; col < N; ++col) | |
cout << m[row][col] << " "; | |
cout << endl; | |
} | |
} | |
bool noRepetitions(TSqMat m) | |
{ | |
int count(TSqMat, int); | |
bool ok = true; | |
int row = 0; | |
while (row < N and ok) { | |
int col = 0; | |
while (col < N and ok) { | |
ok = count(m, m[row][col]) == 1; | |
++col; | |
} | |
++row; | |
} | |
return ok; | |
} | |
int count(TSqMat m, int v) | |
{ | |
int cnt = 0; | |
for (int row = 0; row < N; ++row) | |
for (int col = 0; col < N; ++col) | |
if (m[row][col] == v) | |
++cnt; | |
return cnt; | |
} | |
int sumRow(TSqMat m, int r) | |
{ | |
int s = 0; | |
for (int i = 0; i < N; ++i) | |
s += m[r][i]; | |
return s; | |
} | |
int sumCol(TSqMat m, int c) | |
{ | |
int s = 0; | |
for (int i = 0; i < N; ++i) | |
s += m[i][c]; | |
return s; | |
} | |
int sumDiag(TSqMat m) | |
{ | |
int s = 0; | |
for (int i = 0; i < N; ++i) | |
s += m[i][i]; | |
return s; | |
} | |
int sumAntiDiag(TSqMat m) | |
{ | |
int s = 0; | |
for (int i = 0; i < N; ++i) | |
s += m[i][N-i-1]; | |
return s; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment