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
5 Answers
Reset to default 2Here 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
版权声明:本文标题:loops - Matrix of numbers javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745179454a2646399.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论