Last active
December 10, 2024 11:23
-
-
Save juanfal/a0ae972d1806eb00c3de0d4eef3cd76f to your computer and use it in GitHub Desktop.
first cell sum up neighbours
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.matCent.cpp | |
// juanfc 2024-02-08 | |
// https://gist.github.com/juanfal/a0ae972d1806eb00c3de0d4eef3cd76f | |
#include <iostream> | |
#include <array> | |
using namespace std; | |
const int R = 4; | |
const int C = 3; | |
typedef array<array<int,C>,R> TMat; | |
int main() | |
{ | |
void test(TMat m); | |
test((TMat){{ | |
{{3, 1, 2}}, | |
{{2, 16, 2}}, | |
{{1, 3, 2}}, | |
{{5, 0, 6}} | |
}}); | |
test((TMat){{ | |
{{2, 1, 7}}, | |
{{2, 5, 8}}, | |
{{2, 2, 1}}, | |
{{7, 7, 2}}, | |
}}); | |
test((TMat){{ | |
{{2, 1, 7}}, | |
{{2, 5, 8}}, | |
{{2, 2, 1}}, | |
{{7, 6, 9}}, | |
}}); | |
return 0; | |
} | |
void test(TMat m) | |
{ | |
void firstCent(TMat m, int& the_r, int& the_c); | |
void printMat(TMat m); | |
cout << "Matrix:" << endl; | |
printMat(m); | |
int the_r, the_c; | |
firstCent(m, the_r, the_c); | |
cout << "First cell satisfying the condition: (" | |
<< the_r << ", " << the_c << ")" << endl << endl; | |
} | |
void firstCent(TMat m, int& the_r, int& the_c) | |
{ | |
int sumNeigh(TMat m, int a_row, int a_col); | |
int r = 0; | |
the_r = the_c = -1; | |
while (r < R and the_r == -1) { | |
int c = 0; | |
while (c < C and sumNeigh(m, r, c) != m[r][c]) | |
++c; | |
if (c < C) { // found | |
the_r = r; | |
the_c = c; | |
} else | |
++r; | |
} | |
} | |
int sumNeigh(TMat m, int a_row, int a_col) | |
{ | |
bool isIn(int i, int j); | |
int s = 0; | |
for (int i = -1; i <= 1; ++i) | |
for (int j = -1; j <= 1; ++j) | |
if ((i != 0 or j != 0) | |
and isIn(a_row+i, a_col+j) ) | |
s += m[a_row+i][a_col+j]; | |
return s; | |
} | |
void printMat(TMat m) | |
{ | |
for (int r = 0; r < R; ++r) { | |
for (int c = 0; c < C; ++c) | |
cout << m[r][c] << " "; | |
cout << endl; | |
} | |
} | |
bool isIn(int i, int j) | |
{ | |
return i >= 0 and i < R and | |
j >= 0 and j < C; | |
} | |
// 3 1 2 | |
// 2 16 2 | |
// 1 3 2 | |
// 5 1 6 | |
// First cell satisfying the condition: (1,1) | |
// Matrix: | |
// 2 1 7 | |
// 2 5 8 | |
// 2 2 1 | |
// 7 7 2 | |
// First cell satisfying the condition: (-1,-1) | |
// Matrix: | |
// 2 1 7 | |
// 2 5 8 | |
// 2 2 1 | |
// 7 6 9 | |
// First cell satisfying the condition: (3,2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment