我一直在尝试编写一个解决方案,用javascript编译Euler的问题349(我知道这是一个不太理想的语言)。问题基本上是Langtons蚂蚁,但有10 ^ 18个动作。可以看到对挑战的完整描述here。我设法得到一些工作代码,我使用数组作为方格网格。如果数组中的值为1则为黑色,如果为0,则为白色。现在这个代码的问题是它太慢了,计算100万次移动需要大约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);
答案 0 :(得分:0)