我一直在尝试编写一个解决方案来在 javascript 中投影欧拉的问题 349(我知道这是一种不太理想的语言)。问题基本上是兰顿蚂蚁,但有 10^18 步。可以在此处查看挑战的完整描述。我设法获得了一些工作代码,其中我使用数组作为正方形网格。如果数组中的值为 1 则为黑色,如果为 0 则为白色。现在这个代码的问题是它太慢了,计算一百万次移动大约需要 28 秒。关于如何优化此代码的任何想法?
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);