admin管理员组

文章数量:1418720

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.

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.

Share Improve this question edited Jun 24, 2016 at 14:49 j08691 208k32 gold badges269 silver badges280 bronze badges asked Jun 24, 2016 at 14:47 Yoanna E.Yoanna E. 1452 silver badges5 bronze badges 2
  • print per console.log() or as a string with linebreaks or as document.createElement? – le_m Commented Jun 24, 2016 at 14:51
  • You have 2 answer from 2 different need, on print using console, the second print in html page. – Destrif Commented Jun 24, 2016 at 14:57
Add a ment  | 

5 Answers 5

Reset to default 2

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

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
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/rksLjjzf/

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"

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

本文标签: loopsMatrix of numbers javascriptStack Overflow