我一直在研究魔方计时器网站,我需要做一个加扰算法。我将讨论加扰算法应该如何工作:每张脸都有自己的字母,它是首字母。例如,如果你想移动正面,你会写“F”。如果你想移动右边的脸,你会写“R”,依此类推。只需注意底面是D,至于向下。所以你有 DURLB F。如果那个字母后面什么都没有,你顺时针转动它。如果有撇号“'”,则逆时针转动。如果有一个 2,你转动它两次。现在的问题是你不能有 2 个相同的字母并排在一起,因为它们会取消(例如“.. U U' ...”与什么都不做一样。到目前为止,我已经在我的算法。当你有一个字母时,问题就来了,然后它正好相反,然后是第一个字母,(例如“.. UD U'...”(表示顺时针向上,顺时针向下,逆时针向上))。我不知道如何检查这些并自动避免它们。这是代码:
<div id=“Scramble”></div>
<script>
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
}
</script>