1

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

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

your code works. just take a look into console.log("Input:", [1, 2]); console.log(twoDimensional([1, 2])); output is wrong!!
@zigzag It do works, but your first input is [1, 2] , that should be converted to [ [1,0],[2,0] ]. Look that it's different if your input is: [ [1,2] ]. Check the other answer, the input is [ [1,2] ] as I say.
.as I said , Input: [1,2] => output should be: [[1,2],[0,0]] not [ [1,0],[2,0] ] .other cases works well
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.