PDA

View Full Version : Javascript problem in for loop



Obi Wan
January 27th, 2009, 10:43 PM
Hey everyone I was wondering how I can do the following in javascript below is an example

What I need to do:
XYYYYYX
YXYYYXY
YYXYXYY
YYYXYYY
YYXYXYY
YXYYYXY
XYYYYYX

What I have:



// X & Y THING
function printX()
{
var i=0;
for(i = 0; i<=6; i++)
{
if(i == 0){document.write("<b>X</b>");}
document.write("Y");
if(i == 1){document.write("<b>X</b>");}
document.write("Y");
if(i == 2){document.write("<b>X</b>");}
document.write("Y");
if(i == 3){document.write("<b>X</b>");}
document.write("Y");
if(i == 4){document.write("<b>X</b>");}
document.write("Y");
if(i == 5){document.write("<b>X</b>");}
document.write("Y");
if(i == 6){document.write("<b>X</b>");}
document.write("<br/>");
}
}

// print Y to document
function printY()
{
var j=0;
for(j = 0; j<=6; j++)
{
if(j == 6){document.write("<b>X</b>");}
document.write("Y");
if(j == 5){document.write("<b>X</b>");}
document.write("Y");
if(j == 4){document.write("<b>X</b>");}
document.write("Y");
if(j == 3){document.write("<b>X</b>");}
document.write("Y");
if(j == 2){document.write("<b>X</b>");}
document.write("Y");
if(j == 1){document.write("<b>X</b>");}
document.write("Y");
if(j == 0){document.write("<b>X</b>");}
document.write("<br/>");
}
}
printX();
printY();

Templarian
January 28th, 2009, 03:27 PM
function printX()
{
var s = 7; //Must be odd and its the square size
var x = 0;
var y = 0;
var i = 0; //Increments where to place the X's from the left and right
for(y = 0; y<=s; y++)
{
for(x = 0; x<=s; x++)
{
if(i == x || i = s - x){
document.write("<strong>X</strong>");
}
else
{
document.write("Y");
}
if(i == (s - 1) / 2)
{
i = 0;
}
else
{
i++;
}
}
document.write("<br />");
}
}

Of course I didn't test this and it probably doesn't work, but you get the idea. :lol: