for loop - Javascript matrix -
i trying make matrix has x of x's. following code produces diagonal of x's top left bottom right not top right bottom left. unsure of begin. should for loop created new variable? or there simple adding else if statement variable j? appreciated.
var nmatrix = ""; var n = prompt ("enter number"); n = parseint(n); (var = 1; <= n; i++) { var row = "| "; (var j = 1; j <= n; j++) { if (i == j) row += "x "; //top left bottom right diagonally else row += math.floor (9*math.random()+1)+" "; } row += "|\n"; nmatrix += row; } document.getelementbyid ("matrix").innertext = nmatrix;
how about:
function grid(size) { var out = ""; (var = 0; < size; i++) { (var j = 0; j < size; j++) { out += (i == j || == (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 jsfiddle: https://jsfiddle.net/6w36s1kb/
Comments
Post a Comment