我的解压缩()返回中"0"从何而来?我们如何创建索引翻转的内部循环?



编码挑战:

编写一个函数 unzip,它接受 nRows 行和 nCol 列的矩阵。它应该返回一个新的数组,由 numCol 行和 numRows 列组成,用于对元素进行重新分组。

unzip([
[1, 2],
[3, 4],
]);
// [[1,3],[2,4]]
unzip([
[1, 2, 3],
[4, 5, 6],
]);
// [[1,4],[2,5],[3,6]]
unzip([["a"], ["b"], ["c"]]);
// [['a','b','c']]

我不确定如何实现内部 forloop 逻辑。

我的思考过程:

results[0][0] = arr[0][0] // outer
results[0][1] = arr[1][0] // inner (flipped)
results[1][0] = arr[0][1] // inner (flipped)
results[1][1] = arr[1][1] // outer

尝试:

用 0 预填充结果数组,然后插入正确的值

unzip([[1, 2], [3, 4]]);
function unzip(arr) {
const results = [];
const row = arr[0].length;
const col = arr.length;
for (let i = 0; i < row; i++) {
results.push([0, 0]);
}
for (let i = 0; i < results.length; i++) {
results[i][i] = arr[i][i];
for (let j = results.length - 1; j > i; j--) {
results[i][j] = arr[j][i];
}
}

return results;
} // [ [1, 3], [0, 4]], correct: [[1, 3], [2, 4]]

在我回归中,这个"0"到底从哪里来?原始数组中没有 0

除了 Mike 在注释(方阵)中所说的之外,您的代码从充满 0 的结果开始。然后做,好像结果被填充了初始值,并交换它们。

我的意思是,您的双循环排除了 j

尽可能保持你的逻辑

function unzip(arr) {
const results = [];
const row = arr[0].length;
const col = arr.length;
for (let i = 0; i < row; i++) {
results.push(new Array(col).fill(0));
}
for (let i = 0; i < row; i++) {
for (let j = col - 1; j >= 0; j--) {
results[i][j] = arr[j][i];
}
}

return results;
} 

请注意,我还删除了对result[i][i]的特定处理,这是没有理由的。这只是其他价值中的一个。如果矩阵不是平方的,则失败。并使用您的变量行和列,以避免在循环中也假设它是方形的。

较短的版本(不使用您的逻辑)

function unzip(arr){
result=[];
for(let i=0; i<arr[0].length; i++){
result.push(arr.map((l)=>l[i]));
}
return result;
}

结果的每一行都是 arr 的第 i 列,您可以通过获取l[i]来获得 l,l 是 arr 的所有行。这就是arr.map((l)=>l[i])所做的。

我认为这可以通过双map非常优雅地完成:

const unzip = m => 
(m [0] || []) .map ((c, i) => m .map (r => r [i]))
console .log (unzip ([[1, 2], [3, 4]]))
console .log (unzip ([[1, 2, 3], [4, 5, 6]]))
console .log (unzip ([["a"], ["b"], ["c"]]))
.as-console-wrapper {max-height: 100% !important; top: 0}

我们在第一行(如果输入为空,则映射一个空数组),对于每个列索引,我们返回在行上映射的结果,从每行中提取给定索引处的单元格。

我通常称这个函数为transpose,因为对于非参差不齐的密集二维数组,它充当矩阵转置函数。 但unzip也是一个好名字。

最新更新