Euler Challenge 349: Javascript: Code works but is too slow
I've been trying to code a solution to project Euler's problem 349 in
javascript (I know this is a less than ideal language for this). The
problem is basically Langtons ant but with 10^18 moves. A full description
of the challenge can be seen here . I managed to get some working code
where I use a array as the grid of squares. If a value in the array is 1
then its black, if its 0, its white. Now the problem with this code is it
is much too slow, it takes about 28 seconds to calculate 1 million moves.
Any ideas on how I might go about optimizing this code?
var grid = [];
for (i = 0; i < 1000000; i++) {
grid.push(0);
}
var sum = 0;
var orientation = 0;
var position = (grid.length / 2);
var rowLength = Math.sqrt(1000000);
var mover = function() {
switch (orientation) {
case -360:
position += 1;
break;
case -270:
position += rowLength;
break;
case -180:
position -= 1;
break;
case -90:
position -= rowLength;
break;
case 0:
position += 1;
break;
case 90:
position += rowLength;
break;
case 180:
position -= 1;
break;
case 270:
position -= rowLength;
break;
case 360:
position += 1;
break;
default:
alert("fault in clockwise switch");
}
};
var check = function() {
for (i = 0; i < grid.length; i++) { //counts all blacks (1's)
if (grid[i]) {
sum += 1;
}
}
};
var movement = function() {
for (i = 0; i < 1000000; i++) { // end condition of i is number of
steps
if (grid[position]) //if it lands on a black
{
grid[position] = 0;
if (orientation === 360) { //keeps orientation below 360
orientation = 0;
}
orientation += 90; //90 degree clockwise turn
mover();
} else if (!grid[position]) { //if it lands on a white
if (!grid[position]) {
if (orientation === -360) {
orientation = 0;
}
grid[position] = 1;
orientation -= 90;
mover();
}
}
}
};
movement();
check();
console.log(position);
console.log(sum);
No comments:
Post a Comment