Matrix of numbers javascript

倖福魔咒の 提交于 2020-01-02 07:32:47

问题


I need help with a function in JS that prints a matrix by a given integer N like this:

N = 2;
Matrix: 1 2
        2 3
N = 3;
Matrix: 1 2 3
        2 3 4
        3 4 5

I need to make it with 2 loops but I can't figure out how

function solve(args) {
  var n = args[0];  
}

PS: Sorry for inserting the matrixes into JS code but that way I could visualise the result.


回答1:


Here is the logic

function paintMatrix(n) {

    for (var i = 1; i <= n; i++) {
      var result = "";
      for (var j = 1; j <= n; j++) {
        result += (i + j - 1);
      }
      console.log(result);
    }
}

paintMatrix(3);



回答2:


Consider the following short solution using ES6 Array.fill, Array.map and Array.join functions:

function printMatrix(size){
     if (size <= 1) console.log(size); // if 0/1 was passed in - outputs it as is
     var len = size, count = Array(size).fill(null), matrix = "";

     while (len--) matrix = count.map((v, k) => len + 1 + k).join(" ") +"\n" + matrix;
     console.log(matrix);
 }

 console.log("3 dimensional matrix:");
 printMatrix(3);

 console.log("5 dimensional matrix:");
 printMatrix(5);

The output:

3 dimensional matrix:
1 2 3
2 3 4
3 4 5

5 dimensional matrix:
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9



回答3:


function doMatrix(n){
    var i=0;
    var ret = "";
    for(var x=1+i; x<=n; x++){
      for(var l=x; l<n+x; l++)
           ret += l;
       ret += "\n";
    }
    return ret;
}

https://jsfiddle.net/rksLjjzf/




回答4:


function martix(number) {
    for (var y = 1; y<=number; y++) {
        for (var x = y; x<number + y; x++) {
            var n = x;
            print(n + '&nspb;');
        }
        print('<br />');
    }
}

where "print" would be a function which writes the given input to "somewhere"




回答5:


You can try something like this:

function createMatrix(len){
  var result = [];
  for (var i=0; i<len; i++){
    result.push(new Array(len).fill(i).map(function(item, index){ return item + index}));
  }
  return result;
}

console.log(createMatrix(3))


来源:https://stackoverflow.com/questions/38016201/matrix-of-numbers-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!