Solution only implementing logic of sums, as required, without working with threads .
The logic, as I commented here , to define the secondary diagonals are to check the sum between the position of the line and the column of the element. For example, consider the generic array below:
[ a00 a01 a02 ]
A = [ a10 a11 a12 ]
[ a20 a21 a22 ]
[ a30 a31 a32 ]
Applying the sum of the secondary diagonals, storing the sum in a resultado
array, we have:
resultado[0] = a00
resultado[1] = a10 + a01
resultado[2] = a20 + a11 + a02
resultado[3] = a30 + a21 + a12 + a03
resultado[4] = a31 + a22
resultado[5] = a32
Notice that the sum of i
and j
always results in the position of the resultado
array? That is, for resultado[0]
the sum i+j
is always 0, for resultado[1]
the sum i+j
is always 1, so in succession. So the code would look something like:
#define M 4
#define N 3
#define Z M+N-1
int main(int argc, char const *argv[]) {
int mat[M][N] = {
{ 1, 2, 3},
{ 4, 5, 6},
{ 7, 8, 9},
{10, 11, 12}
};
int result[Z] = {0};
// z varia de 0 a M+N-1, exclusive
// Indica a linha na matriz resultados:
for (int z = 0; z < Z; z++) {
// i varia de 0 a M, exclusive
// Indica a linha na matriz mat:
for (int i = 0; i < M; i++) {
// j varia de 0 a N, exclusive
// Indica a coluna na matriz mat:
for (int j = 0; j < N; j++) {
// Se a soma da posição for igual a z:
if (i + j == z) {
// Incrementa a soma:
result[z] += mat[i][j];
}
}
}
// Exibe o resultado da soma:
printf("%2d\n", result[z]);
}
return 0;
}
When executing the code, the output will be:
1
6
15
24
20
12
Note : The question image has the wrong result in the fourth line, since the sum should be 10+8+6
and 10+9+6
.
To implement logic with threads , instead of you iterating over the value of z
, you create the T
threads , where each is responsible for calculating a particular result position. You could even define a function to calculate a specific diagonal:
int sum(int z, int mat[M][N]) {
int result = 0;
// i varia de 0 a M, exclusive
// Indica a linha na matriz mat:
for (int i = 0; i < M; i++) {
// j varia de 0 a N, exclusive
// Indica a coluna na matriz mat:
for (int j = 0; j < N; j++) {
// Se a soma da posição for igual a z:
if (i + j == z) {
// Incrementa a soma:
result += mat[i][j];
}
}
}
return result;
}
And make calls of result[0] = sum(0, mat)
, result[1] = sum(1, mat)
, ..., in threads .
See working at Ideone .