I have got a little function in java script and I want to split an array A into a 2d array(square array).
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;
}
I want to get an array from input and converts it to a square array.
Matrices should be padded on the right or at the bottom, but not both simultaneously (for example the size of the biggest direction shouldn't change).
If the input is already a square matrix, just return that matrix.
for example:
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]]
could you help me How I can change my Function to get above outputs?
any solutions would be my appreciated
CodePudding user response:
Here is how I'd do it.
//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('---');
}
CodePudding user response:
Try this:
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]]));