我在 java 腳本中有一個小函式,我想將陣列 A 拆分為二維陣列(方形陣列)。
function twoDimensional(array, row) {
let newArray = [];
let arraySize = Math.floor(array.length / row);
let extraArraySize = array.length % row;
while (array.length) {
if (!!extraArraySize) {
newArray.push(array.splice(0, arraySize 1));
extraArraySize--;
} else {
newArray.push(array.splice(0, arraySize));
}
}
return newArray;
}
我想從輸入中獲取一個陣列并將其轉換為一個方形陣列。
矩陣應在右側或底部填充,但不能同時填充(例如,最大方向的大小不應改變)。
如果輸入已經是方陣,則回傳該矩陣。
例如:
Input: [1,2] => output : [[1,2],[0,0]]
Input: [[6,2],[4,9]] => output : [[6,2],[4,9]]
Input: [[3,2],[9,9],[4,8]] => output : [[3,2,0],[9,9,0],[4,8,0]]
你能幫我如何改變我的功能以獲得以上輸出嗎?
任何解決方案將不勝感激
uj5u.com熱心網友回復:
這是我的做法。
//input output pairs
const ioPairs = [{
input: [[1,2]],
output: [[1,2],[0,0]]
}, {
input: [[6,2],[4,9]],
output: [[6,2],[4,9]]
}, {
input: [[3,2],[9,9],[4,8]],
output: [[3,2,0],[9,9,0],[4,8,0]]
}];
//solution
function squareMatrix(input) {
const output = [];
const size = Math.max(input.length, input[0].length);
for (let row of input) {
//pad right
row = [...row];
while (row.length < size) {
row.push(0);
}
output.push(row);
}
//pad bottom
while (output.length < size) {
const blanks = (new Array(size)).fill(0);
output.push(blanks);
}
return output;
}
//testing
for (let ioPair of ioPairs) {
const actualOutput = squareMatrix(ioPair.input);
const expectedOutput = ioPair.output;
console.log('input:', ioPair.input);
if (JSON.stringify(actualOutput) === JSON.stringify(expectedOutput)) {
console.log('output:', actualOutput);
} else {
console.log('actualOutput:', actualOutput);
console.log('expectedOutput:', expectedOutput);
}
console.log('---');
}
uj5u.com熱心網友回復:
試試這個:
function twoDimensional(array) {
let newArray = [];
let matrixSize = array.length;
array.forEach((element) => {
if (element.length && element.length > matrixSize) {
matrixSize = element.length;
}
});
for (let i = 0; i < matrixSize; i ) {
let row = array[i] || [];
if (typeof array[i] === "number") {
row = [array[i]];
}
let toFill = matrixSize - row.length;
while (toFill > 0) {
row.push(0);
toFill--;
}
newArray.push(row);
}
return newArray;
}
console.log("Input:", [1, 2]);
console.log(twoDimensional([1, 2]));
console.log("Input:", [[6, 2],[4, 9]]);
console.log(twoDimensional([[6, 2],[4, 9]]));
console.log("Input:", [[3, 2],[9, 9],[4, 8]]);
console.log(twoDimensional([[3, 2],[9, 9],[4, 8]]));
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/463694.html
標籤:javascript 矩阵
