魔方加扰生成器算法

Rubik's Cube Scramble Generator algorithm

本文关键字:算法 魔方      更新时间:2023-10-16

我最近在做一个项目,其中包括一个魔方加扰生成器。基本上,程序应该生成并显示随机立方体符号,以便用户可以跟随每个动作并拥有一个相当混乱的立方体。符号包括"R"表示右层,"L"表示左层,"F"表示向前层,"D"表示向下,"U"表示向上,"B"表示后层。所以你总共有 6 个边"R、L、U、D、F、B"。这些符号中的任何一个后面的撇号表示逆时针移动该层,"2"表示将该层移动两次。问题是你不能像"R,R"那样让相同的符号彼此相邻重复,因为它与"R2"相同,也不能让"R,R"彼此相邻,因为它们会相互抵消。我的解决方案是制作一个二维数组,用于存储每种类型的 3 组符号。

string notation_group[row][column] = { { "R ", "L ", "F ", "B ", "U ", "D " },
{"R' ", "L' ", "F' ", "B' ", "U' ", "D' "}, { "R2", "L2", "F2", "B2", "U2", "D2"} };

这意味着,每当程序从这些组中任何一个中选择随机列时,程序都必须防止下一个生成的符号在任何其他组中选择相同的列。因此,假设程序选择第一组"R"的第一个元素,那么对于下一次迭代,它可以选择除"R","R"和"R2"之外的任何符号,所有这些都属于其各自组的第一列。因此,程序所要做的就是在下一次迭代期间不要选择该列。

我使用了一个"temp"变量来记住当前随机生成的符号,并将其与下一个符号进行比较,并在它们相等时生成一个新的符号。

int temp;
scrambled_notation[i] = notation_group[pickGroup][pickColumn];
temp = pickColumn;
pickColumn = 0 + rand() % 6;
while (temp == pickColumn) {
pickColumn = 0 + rand() % 6;
}

它确实有效,但还有另一个问题,每当你有像"R,L"或"R,L',R"这样的东西在彼此旁边重复多次时,它们会再次相互抵消,对立方体没有任何影响。有什么想法可以防止两个对立的双方重复不止一次吗?我将非常感谢您的帮助。

void initScramble(const int, string[][6], string[]);
int main() {
srand(time(0));
const int row = 3, column = 6;
string notation_group[row][column] = { { "R", "L", "F", "B", "U", "D" },
{"R'", "L'", "F'", "B'", "U'", "D'"}, { "R2", "L2", "F2", "B2", "U2", "D2"} };
const int scrambleSize = 22;
string scrambled_notation[scrambleSize];
cout << "SCRAMBLE: " << endl;
initScramble(scrambleSize, notation_group, scrambled_notation);
system("pause");
return 0;
}
void initScramble(const int scrambleSize, string notation_group[][6], string scrambled_notation[]) {
int pickColumn = 0 + rand() % 6;
while (true) {
cin.get();
for (int i = 0; i < scrambleSize; i++) {
int pickGroup = 0 + rand() % 3;
int temp;
scrambled_notation[i] = notation_group[pickGroup][pickColumn];
temp = pickColumn;
pickColumn = 0 + rand() % 6;
while (temp == pickColumn) {
pickColumn = 0 + rand() % 6;
}
}
for (int i = 0; i < scrambleSize; i++) {
cout << scrambled_notation[i] << "  ";
}
cin.get();
system("CLS");
}
}

你必须寻找最后两个移动,只要它们是可交换的。如果没有,则仅检查最后一步。这通过每对列都是可交换的这一事实来简化:

void initScramble(const int scrambleSize, string notation_group[][6], string scrambled_notation[]) {
while (true) {
int lastColumn = 7; // Invalid columns
int beforeLastColumn = 7;
cin.get();
for (int i = 0; i < scrambleSize; i++) {
int pickGroup = 0 + rand() % 3;
int pickColumn = 0 + rand() % 6;
bool isCommutative = (lastColumn / 2) == (beforeLastColumn / 2);
while (pickColumn == lastColumn || isCommutative && pickColumn == beforeLastColumn) {
pickColumn = 0 + rand() % 6;
}
scrambled_notation[i] = notation_group[pickGroup][pickColumn];
beforeLastColumn = lastColumn;
lastColumn = pickColumn;
}
for (int i = 0; i < scrambleSize; i++) {
cout << scrambled_notation[i] << "  ";
}
cin.get();
system("CLS");
}
}

您不必再看,因为按照您的加扰规则,您只能有 2 个交换连续移动。例如,"L,R,L"和"L,R,R"将被丢弃,因此,将永远不会生成 3 个交换移动。