1

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

问题是不能有两个相同的字母彼此相邻,即使它们在不同的方向也不行。例如,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

}
4

1 回答 1

1

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

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>

希望能帮助到你。

于 2017-10-19T17:55:42.257 回答