M56035G M56035G - 2 months ago 7
jQuery Question

how to create matrix/array of array with fix number of rows and non-fixed number of columns?

here am trying to create mtrix with fixed number of rows and non-fixed number of columns like bellow.


var matrix=[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0,0 ]]


am trying this code


function matrix1(m, n) {
for ( m = 9;m>0;m--)
{
for (var n=m;n>0; n--)
{
return Array.from({
length: m
}, () => new Array(n).fill(0));
}
document.write("<br>");
}
};

var cols=9
var counter=9;
matrix(counter,cols);


and am expecting the output of this code is as like


var matrix=[[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0],
[0, 0],
[0]]


and am getting output as


var matrix=[[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]]


whats wrong with my code?

Answer

Just small modification in your code

function matrix(m, n) {
 var arr = [];
 for (  m = 9; m>0; m--)
    {
      for (var n = m;n>0; n--)
         {
           arr.push(new Array(n).fill(0))
         }
       return arr;
    }  
 };

var cols=9
var counter=9;
console.log(matrix(counter,cols));

This will work

Working live example : https://jsbin.com/?html,js,output

Hope this helps. Thanks !