joe19995
joe19995

Reputation: 1

set value for matrix into function in C

I need to allocate 0 , at random, within a matrix like a:

   Matrix a                 Matrix b
    1 3 5                    1 0 5
    6 7 2    --setBoard->    0 0 2    // counterZeros = 5
    9 3 1                    9 0 0

but i need to handle the number of zeros, for the returned matrix, my idea is to iterate until it reaches the requested number of zeros (in this case would be 5 zeros ) and break the loop(while(breaker==0)) i have this code:

void setBoard(int **boardMatrix, int N){
    int counterZeros = 0;
    int i, j;
    int breaker = 0;
    while(breaker == 0) {
        for (i = 0; i < N; i++) {
            for (j = 0; j < N; j++) {
                if(boardMatrix[i][j] != 0) {
                    if(i == randomNum(N)) { // generate random number [0,N]
                        boardMatrix[i][j] = 0;
                        counterZeros++;
                        if(counterZeros = 5) breaker = 1;
                    }
                }
            }
        }
    }
    printf("\n Numero vacias: _%d_\n", counterZeros);
}

example call:

int **matrix = (int**)malloc(N*sizeof(int*));     //matrix 3x3
for (i=0;i<N;i++) matrix[i] = (int*)malloc(N*sizeof(int));

genBoard(matrix,3); //here make the matrix to "matrix a"
printM(matrix);
setBoard(matrix,3); //after this function should return the matrix with the given number of zeros ( "5" )  "matrix b"
printM(matrix);

when I called the function , the counterZeros reaches "5" shown by the print , but the matrix dont have "5" zeros

Upvotes: 0

Views: 66

Answers (1)

Darktega
Darktega

Reputation: 106

Your problem is in the loop condition, while (breaker == 5) will run only if breaker is 5. Also,

                    if(counterZeros = 5) breaker=1;

Comparission is invalid and you would be assigning breaker the value of 1 everytime.

Upvotes: 1

Related Questions