Find cells with odd values in a matrix

in #steempress4 years ago (edited)


Problem Statement:-

Given n and m which are the dimensions of a matrix initialized by zeros and given an array indices where indices[i] = [ri, ci]. For each pair of [ri, ci] you have to increment all cells in row ri and column ci by 1.

Return the number of cells with odd values in the matrix after applying the increment to all indices.

 

Example 1:

Matrix example 1

 

Input: n = 2, m = 3, indices = [[0,1],[1,1]]

Output: 6

Explanation: Initial matrix = [[0,0,0],[0,0,0]].

After applying first increment it becomes [[1,2,1],[0,1,0]].

The final matrix will be [[1,3,1],[1,3,1]] which contains 6 odd numbers.

 

Example 2:
Example 2
Matrix example 2

 

Input: n = 2, m = 2, indices = [[1,1],[0,0]]

Output: 0

Explanation: Final matrix = [[2,2],[2,2]]. There is no odd number in the final matrix.

 

Constraints:

  • 1 <= n <= 50
  • 1 <= m <= 50
  • 1 <= indices.length <= 100
  • 0 <= indices[i][0] < n
  • 0 <= indices[i][1] < m
 

 

Below is an algorithm in Javascript:

 

  • Initialize the output matrix
 
  • Loop through and extract the ith row and columns
 
  • Increment the cells in the ith row and ith columns obtained from previous step by 1
 
  • Check the matrix cells by looping through the entries, increment the counter if the entry is odd and return the count
 
/**
 * @param {number} n
 * @param {number} m
 * @param {number[][]} indices
 * @return {number}
 */
var oddCells = function(n, m, indices) {
    var matrix = zeros([n,m]);
var count = 0;

for (var i = 0; i &lt; indices.length; i++) {
    var row = indices[i][0];
    var col = indices[i][1];
    
    matrix = incrementCells(n, m, row, col, matrix);
}
for (var i = 0; i &lt; n; i++) {
    for (var j = 0; j &lt; m; j++) {
        if (matrix[i][j] % 2 !== 0)
            count++;
    }
}
return count;

};

var incrementCells = function(n, m, row, col, matrix) {
for (var i = 0; i < m; i++) {
matrix[row][i]++;
}

for (var j = 0; j &lt; n; j++) {
    matrix[j][col]++;
}

return matrix;

}

var zeros = function(dimensions) {
var array = [];

for (var i = 0; i &lt; dimensions[0]; ++i) {
    array.push(dimensions.length == 1 ? 0 : zeros(dimensions.slice(1)));
}

return array;

}

 

Like us on:- https://facebook.com/golibraryco to receive regular updates.


Posted from my blog with SteemPress : https://www.golibrary.co/find-cells-with-odd-values-in-a-matrix/

Sort:  

According to the Bible, Bro. Eli Soriano: The Marks and Proofs of a Blessed Reader

Watch the Video below to know the Answer...

(Sorry for sending this comment. We are not looking for our self profit, our intentions is to preach the words of God in any means possible.)


Comment what you understand of our Youtube Video to receive our full votes. We have 30,000 #SteemPower. It's our little way to Thank you, our beloved friend.
Check our Discord Chat
Join our Official Community: https://steemit.com/created/hive-182074