如何保证我的魔方加扰算法不会连续两次选择相同的方向?



我正在开发一个魔方计时器网站(JavaScript),它需要一个加扰算法。如果只是从数组中随机挑选字母,这会很容易,但它需要满足一些要求。每个字母表示魔方算法符号中的一个移动,因此例如"L"表示顺时针移动左侧。或者"U2"表示将上侧移动两次,"B'"表示将后侧逆时针移动。等等

问题是,不可能有两个相同的字母相邻,即使它们的方向不同。例如,U不能紧挨着U',或者U2等等。它必须是不同的字母。有时,我的代码会生成两个相邻的相同字母。

这是我的代码:

function generateScramble() {
//Possible Letters
var array = new Array(" U", " D", " R", " L", " F", " B", " U'", " D'", " R'", " L'", " F'", " B'", " U2", " D2", " R2", " L2", " F2", " B2"); 
var array2 = new Array(); // The Scramble.
var rdArr = new Array(); // The Array of random numbers.
for (var i = 0; i < 20; i++) {
var random = Math.floor(Math.random() * array.length);
rdArr.unshift(random);
if (rdArr[1] - rdArr[0] == 0 ||
rdArr[0] - rdArr[1] == 0 ||
rdArr[1] - rdArr[0] == 6 ||
rdArr[0] - rdArr[1] == 6 ||
rdArr[1] - rdArr[0] == 12 ||
rdArr[0] - rdArr[1] == 12) { // Check whether a D is next to D' or D2, or if F is next to F' or F2, R next to R' or R2, and so on
if (random < 17) {
random++;
} else {
random--;
}
}
array2.push(array[random]); // Get letters in random order in the array.
}
var scramble = "Scramble: " + array2[0] + array2[1] + array2[2] + array2[3] + array2[4]
+ array2[5] + array2[6] + array2[7] + array2[8] + array2[9]
+ array2[10] + array2[11] + array2[12] + array2[13] + array2[14]
+ array2[15] + array2[16] + array2[17] + array2[18] + array2[19];
document.getElementById("Scramble").innerHTML = scramble; // Display the scramble
}

我认为,代码可以是这样的:

generateScramble();
function generateScramble() {
// Possible Letters
var array = new Array(" U", " D", " R", " L", " F", " B")
// Possible switches
var switches = ["", "'", "2"]; 
var array2 = new Array(); // The Scramble.
var last = ''; // Last used letter
var random = 0;
for (var i = 0; i < 20; i++) {
// the following loop runs until the last one 
// letter is another of the new one
do {
random = Math.floor(Math.random() * array.length);
} while (last == array[random]) 
// assigns the new one as the last one
last = array[random];
// the scramble item is the letter
// with (or without) a switch
var scrambleItem = array[random] + switches[parseInt(Math.random()*switches.length)];
array2.push(scrambleItem); // Get letters in random order in the array.
}
var scramble = "Scramble: ";

// Appends all scramble items to scramble variable
for(i=0; i<20; i++) {
scramble += array2[i];
}

document.getElementById("Scramble").innerHTML = scramble; // Display the scramble
}
<div id="Scramble"></div>

希望能有所帮助。

相关内容

  • 没有找到相关文章

最新更新