Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

155
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda