3
Hey there, guys. I have an exercise where I must populate a matrix with random numbers from 0 to 9 and then replace the repeated numbers (except the first time the number appears) with the number 0.
The first part I managed to do, but I’m having difficulty zeroing the repeated values. Follow the code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
main ()
{
int N, random, coluna, linha, temp, l, k;
printf("Insira o tamanho da matriz\n");
scanf("%d", &N);
int matriz[N][N];
srand(time(NULL));
// Populei a matriz com números aleatórios
for (coluna = 0 ; coluna < N ; coluna++){
for(linha = 0 ; linha < N ; linha++){
random = rand () % 10;
matriz[coluna][linha] = random;
printf("%d ", matriz[coluna][linha]);
}
printf("\n");
}
printf("\n\n\n");
// A maneira que pensei para comparar a matriz não deu muito certo...
for (coluna = 0 ; coluna < N ; coluna++){
for (linha = 0 ; linha < N ; linha++){
for (k = coluna ; k < N ; k++){
for (l = 1 ; l < N ; l++){
if (matriz[coluna][linha] == matriz[k][l]){
matriz[coluna][linha] = 0;
}
}
}
}
}
for (coluna = 0 ; coluna < N ; coluna++){
for(linha = 0 ; linha < N ; linha++){
printf("%d ", matriz[coluna][linha]);
}
printf("\n");
}
}
This code will also be faster than four
for
one inside the other.– Kyle A
Hi! I understand much of the code, except lines 40-44, which is the part that changes the number by 0. If the counter at [cl][ln] position of the matrix increases, the matrix [cl][ln] turns 0... But why the counter increases?
– Dervel
@1) The condition of the
if
isse o contador for diferente de zero
; 2) The meter shall be incremented only after the evaluation of theif
.– Lacobus
@This is an equivalent code:
if( ++cont[ matriz[cl][ln] ] > 1 ) matriz[cl][ln] = 0;
– Lacobus
@Lacobus I think I now understand. If the counter is greater than 1, it Zera the matrix. That’s it?
– Dervel
Exactly @Dervel! stay tuned for the increment operator
++
, when it is using before the variable (ex.:++i;
), the increment happens before the evaluation of the expression (pre-increment), when it is used after the variable (ex.:i++;
), the increment happens after the evaluation of the expression (post-increment).– Lacobus
@Dervel "Simplicity is the ultimate sophistication." Leonado da Vinci
– Lacobus
@Lacobus I’m trying to do it in a more simplified (or, ugly, how to prefer hehe) way. Can I increment the cont before the if? I tried that way, but it wasn’t...
for( cl = 0; cl < MAX_COLS; cl++ )
 for( ln = 0; ln < MAX_LINS; ln++ )
 cont[matriz[cl][ln]]++;
 if(cont[matriz[cl][ln]] > 1 ){
 matriz[cl][ln] = 0;
 }
– Dervel
@Dervel The keys are missing:
for( cl = 0; cl < MAX_COLS; cl++ ) { for( ln = 0; ln < MAX_LINS; ln++ ) { cont[ matriz[cl][ln] ]++; if( cont[ matriz[cl][ln] ] > 1 ) { matriz[cl][ln] = 0; } } }
– Lacobus