JSFiddle - React, Tailwind, and code Playground
by kkdaily
HTML
<h3>
(CTCI 1.8) write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0
</h3>
<div id="message"></div>
CSS
#message {
padding: 10px;
}
.success {
background-color: lightgreen;
}
.failure {
background-color: pink;
}
JavaScript
/*
ex: [[1, 0], [2, 3]] => [[0, 0], [2, 0]]
0. create vars affectedRows = [] and affectedColumns = []
1. iterate through each element in the matrix. if the element is 0, then get the current row and column positions and push them into affectedRows and affectedColumns
2. once done iterating, loop through affectedRows and change all elements in the matching rows to 0
3. loop through affectedColumns and change all elements in the matching columns to 0
*/
zero = (matrix) => {
const affectedRows = []
const affectedColumns = []
let zeroMatrix = matrix
for (let row = 0; row < matrix.length; row++) {
console.log('testing')
for (let column = 0; column < matrix[row].length; column++) {
console.log('test')
if (matrix[row][column] === 0) {
affectedRows.push(row)
affectedColumns.push(column)
}
}
}
affectedRows.forEach((row) => {
matrix[row].forEach((column) => {
zeroMatrix[row][column] = 0
})
})
affectedColumns.forEach((column) => {
matrix.forEach((row, i) => {
zeroMatrix[i][column] = 0
})
})
return zeroMatrix
}
// TESTS
test = (method, inputs, expected) => {
const messageEl = document.getElementById('message')
let status = 'success'
let actual
if (inputs.length > 1) {
actual = method(...inputs)
} else {
actual = method(inputs[0])
}
if (actual.toString() !== expected.toString()) {
messageEl.innerText = `Test failed for input ${inputs}. Expected: ${expected}. Actual: ${actual}`
messageEl.classList.add('failure')
status = 'fail'
}
if (status === 'success') {
messageEl.innerText = 'All tests passed!'
messageEl.classList.add('success')
}
}
test(zero, [ [[1, 2], [3, 4], [0, 0]] ], [[0, 0], [0, 0], [0, 0]])
test(zero, [ [[0, 3, 4], [6, 7, 9], [8, 8, 8]] ], [[0, 0, 0], [0, 7, 9], [0, 8, 8]])
/* test(zero, ['ab'], 'ab')
test(zero, ['aaa'], 'a3') */