我正在尝试完成 CodeSignal 街机中的一项挑战,该挑战接受具有整数值的多维数组并添加这些索引的值。如果索引 = 0,我需要忽略该索引以及该特定索引以下的所有索引。例如:
array = [
[0, 1, 2],
[1, 0, 3],
[3, 1, 0]
];
我遇到的问题是定位 COLUMN 中从值为 0 的索引开始的所有索引。使用这个数组,我应该得到 6 的输出。这是我到目前为止所得到的:
function matrixElementsSum(matrix) {
const checkHaunt = [];
for (let c = 0; c < matrix.length; c++) {
// console.log(`Matrix: ${matrix[c]}`)
for (let i = 0; i < matrix[c].length; i++) {
// console.log(`index: ${matrix[c][i]}`)
if (matrix[c][i] != 0 && c == 0) {
checkHaunt.push(matrix[c][i]);
}
else if (matrix[c][i] != 0 && matrix[c-1][i] != 0) {
checkHaunt.push(matrix[c][i]);
}
}
}
return checkHaunt.reduce((a, b) => a + b, 0);
}
我最初认为我需要忽略直接低于 0 值的任何索引,但我读错了指令。使用此代码,我将通过上述数组得到 9 的输出。
任何关于添加代码以定位我需要的索引的建议将不胜感激。
最佳答案
如果我正确理解您的要求,我会采取稍微不同的方法 - 当您遇到包含零的列时跟踪它们;否则添加到 sum 变量:
const array = [
[0, 1, 2],
[1, 0, 3],
[3, 1, 0]
];
function matrixElementsSum(matrix) {
let sum = 0;
const zeroCols = new Set();
matrix.forEach(row => {
row.forEach((val, i) => {
if (val === 0) {
zeroCols.add(i);
} else if (!zeroCols.has(i)) {
sum += val;
}
});
});
return sum;
}
console.log(matrixElementsSum(array));
>>> 6
关于JavaScript - 特定索引下方的多维数组的列中的目标索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60479241/