|
| 1 | +/*Write an algorithm such that if an element |
| 2 | + in an M*N matrix is 0,it's entire row and column |
| 3 | + are set to 0*/ |
| 4 | + |
| 5 | +const zeroMatrix = (nestedArr) => { |
| 6 | + var rowsAndColsWithZeros = checkForZeroIndex(nestedArr); |
| 7 | + let rowLength = nestedArr[0].length; |
| 8 | + let columnLength = nestedArr.length; |
| 9 | + for (let i = 0; i < rowsAndColsWithZeros['rows'].length; i++) { |
| 10 | + let rowIndex = rowsAndColsWithZeros['rows'][i]; |
| 11 | + for (let x = 0; x < rowLength; x++) { |
| 12 | + nestedArr[rowIndex][x] = 0; |
| 13 | + } |
| 14 | + } |
| 15 | + for (let i = 0; i < rowsAndColsWithZeros['columns'].length; i++) { |
| 16 | + let colIndex = rowsAndColsWithZeros['columns'][i]; |
| 17 | + for (let x = 0; x < columnLength; x++) { |
| 18 | + nestedArr[x][colIndex] = 0; |
| 19 | + } |
| 20 | + } |
| 21 | + return nestedArr; |
| 22 | + |
| 23 | + // **** Helper functions **** |
| 24 | + function checkForZeroIndex(nestArr) { |
| 25 | + let zeroIndices = {rows: [], columns: []}; |
| 26 | + for (let i = 0; i < nestArr.length; i++) { |
| 27 | + for (let x = 0; x < nestArr[i].length; x++) { |
| 28 | + if (nestArr[i][x] === 0) { |
| 29 | + zeroIndices['rows'].push(i); |
| 30 | + zeroIndices['columns'].push(x); |
| 31 | + } |
| 32 | + } |
| 33 | + } |
| 34 | + return zeroIndices; |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +// **** TESTS ****: |
| 39 | + |
| 40 | +var testArr1 = [ |
| 41 | + [3, 5, 6], |
| 42 | + [1, 0, 2], |
| 43 | + [4, 4, 5], |
| 44 | + [2, 2, 2], |
| 45 | +] |
| 46 | + |
| 47 | +var resultArr1 = [ |
| 48 | + [3, 0, 6], |
| 49 | + [0, 0, 0], |
| 50 | + [4, 0, 5], |
| 51 | + [2, 0, 2], |
| 52 | +] |
| 53 | + |
| 54 | +var testArr2 = [ |
| 55 | + [3, 5, 6], |
| 56 | + [1, 0, 2], |
| 57 | + [4, 4, 0], |
| 58 | + [2, 0, 2], |
| 59 | +] |
| 60 | + |
| 61 | +var resultArr2 = [ |
| 62 | + [3, 0, 0], |
| 63 | + [0, 0, 0], |
| 64 | + [0, 0, 0], |
| 65 | + [0, 0, 0], |
| 66 | +] |
| 67 | + |
| 68 | +var testArr3 = [ |
| 69 | + [3, 5, 6], |
| 70 | + [0, 0, 2], |
| 71 | + [4, 4, 0], |
| 72 | + [2, 0, 2], |
| 73 | +] |
| 74 | + |
| 75 | +var resultArr3 = [ |
| 76 | + [0, 0, 0], |
| 77 | + [0, 0, 0], |
| 78 | + [0, 0, 0], |
| 79 | + [0, 0, 0], |
| 80 | +] |
| 81 | +console.log(JSON.stringify(zeroMatrix(testArr1)) === JSON.stringify(resultArr1)); |
| 82 | +console.log(JSON.stringify(zeroMatrix(testArr2)) === JSON.stringify(resultArr2)); |
| 83 | +console.log(JSON.stringify(zeroMatrix(testArr3)) === JSON.stringify(resultArr3)); |
| 84 | +console.log(JSON.stringify(zeroMatrix([[]])) === JSON.stringify([[]])); |
0 commit comments