編碼挑戰:
撰寫一個函式 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
uj5u.com熱心網友回復:
除了 Mike 在評論中所說的(方陣)之外,您的代碼從一個滿是 0 的結果開始。然后就像結果填充了初始值一樣,并交換它們。
我的意思是,您的雙回圈排除了 j<i. 然而,它只影響result[i][j]. 那么,result[i][j]當 j<i 時應該如何獲得非 0 值?
盡可能保持你的邏輯
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],這是沒有理由的。這只是其他價值之一。如果矩陣不是正方形,則失敗。并使用您的變數 row 和 col,以避免在回圈中也假設它是方形的。
較短的版本(不使用您的邏輯)
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 是 arr 的所有行來得到。這是做什么arr.map((l)=>l[i])的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/520444.html
上一篇:如何在字串中添加值
下一篇:如何降低此演算法的時間復雜度?
