mastodon mastodon - 5 years ago 604
Javascript Question

Javascript matrix

I am trying to make a matrix which has an X of X's. The following code produces a diagonal of X's from the top left to the bottom right but not from the top right to the bottom left. I am unsure of where to even begin. Should another for loop be created with a new variable? Or is there something as simple as adding an else if statement for variable j? Any help will be greatly appreciated.

var nMatrix = "";
var n = prompt ("enter a number");
n = parseInt(n);
for (var i = 1; i <= n; i++) {
var row = "| ";
for (var j = 1; j <= n; j++) {
if (i == j)
row += "x "; //top left to bottom right diagonally
else
row += Math.floor (9*Math.random()+1)+" ";
}
row += "|\n";
nMatrix += row;
}
document.getElementById ("matrix").innerText = nMatrix;

Answer Source

How about:

function grid(size) {
    var out = "";
    for (var i = 0; i < size; i++) {
        for (var j = 0; j < size; j++) {
            out += (i == j || i == (size - j - 1)) ? "X" : " ";
        }
        out += "\n";
    }
    return out;
}

Output of grid(9):

X       X
 X     X 
  X   X  
   X X   
    X    
   X X   
  X   X  
 X     X 
X       X

Here's a jsfiddle: https://jsfiddle.net/6w36s1kb/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download