MoveAndTurn Part2

Yesterday, based on the same Advanced Placement pop quiz I programmed the algorithm for the “greedy” random path generation in Javascript.

function newPath(){
var i,j,counter;
var whiteId;
var x;

for (i=1; i<6; i++)
for (j=1; j<6; j++)
document.getElementById(i.toString().concat(j.toString())).style.backgroundColor = "black";

i = 1;
j = 1;

x = document.getElementById("11");
x.style.backgroundColor="white";
x = document.getElementById("55");
x.style.backgroundColor="gray";

for (counter = 0; counter<7; counter++)
{
if (Math.floor(Math.random()*2)==1)
{
if (j < 5)
{
j++;
whiteId = i.toString().concat(j.toString());
x = document.getElementById(whiteId);
x.style.backgroundColor = "white";
}
else
{
i++;
whiteId = i.toString().concat(j.toString());
x = document.getElementById(whiteId);
x.style.backgroundColor = "white";
}
}
else
{
if (i < 5)
{
i++;
whiteId = i.toString().concat(j.toString());
x = document.getElementById(whiteId);
x.style.backgroundColor = "white";
}
else
{
j++;
whiteId = i.toString().concat(j.toString());
x = document.getElementById(whiteId);
x.style.backgroundColor = "white";
}

}
}
}

See it live in jsfiddle.net here.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s