1

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?

2 Answers 2

1

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 !

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

2 Comments

Thanks,@KrishCdbry
Most Welcome @M56035G :)
1

You can use a combination of array.map and array.fill

function createMatrix(m, n) {
  return new Array(m).fill('').map(function(el, index) {
    return n > index ? new Array(n - index).fill(0) : [];
  });
}
console.log(createMatrix(7, 7))

2 Comments

this is exclt what i was trying,but this code create minimum column sized array with 3,what if i want it till 1
Thanks @Rajesh it is realy helpfull

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.