Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
transform an array to square matrix(2D matrix) by function

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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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('---');
}

about 4 years ago · Juan Pablo Isaza Report

0

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]]));

about 4 years ago · Juan Pablo Isaza Report

0

What you mean is probably transform a rectangular matrix to a square matrix by the output you've provided.

let test1 = [
    [1, 2],
    [3, 4],
    [5, 6],
];

let test2 = [
    [1, 2, 3],
    [4, 5, 6],
];

let test3 = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
];

console.log(toSquareMatrix(test1));
console.log(toSquareMatrix(test2));
console.log(toSquareMatrix(test3));

function toSquareMatrix(args) {
    let colCount = args[0].length;
    let rowCount = args.length;
    let result = [];

    if (colCount === rowCount) {
        return "You already have a square matrix";
    } else if (rowCount > colCount) {
        result = args.map((row) => {
            while (row.length /**col */ < rowCount) {
                row.push(0);
            }
            return row;
        });
    } else if (colCount > rowCount) {
        while (args.length < colCount) args.push(Array(colCount).fill(0));
        result = args;
    }
    return result;
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!