基本上我正在做的是尝试通过广泛搜索所有可能的移动来解决魔方。我知道这不是解决立方体的最佳方法,但我只需要非常短的序列(所以搜索的深度不可能比3更深),而且我不需要存储除了目前的顺序。
我正试图找到一种打印出越来越多的数字字符串(0,1,2,00,01,02 ...)的方法,所以我可以将每个字符串插入一个函数来检查是否存在特定的移动序列解决了立方体问题,但我无法找到一种无限期地延续序列的方法。
到目前为止,我所管理的所有内容都是嵌套for循环,但每次搜索越深时都需要有另一个循环。有谁知道如何处理这个问题?
对不起,如果我太模糊了,我可以写一篇关于我想要做的文章,但我想我会尽量保持简单。
答案 0 :(得分:0)
听起来你想要一个递归解决方案,这样你的函数会在给定序列作为输入的情况下生成一个后继移动列表,在这种情况下,你可以根据需要多次在自己的输出上调用该函数。
答案 1 :(得分:0)
递归函数不会这样做吗?您可以限制递归的深度并逐渐加深它。
[Update]将函数传递给指定深度的int;每次递归时,递减值 - 检查它是否为零,如果是,则返回。
对于值,将字符串或字符串构建器的集合传递给递归函数。每个级别读取(并移除)上一级别的值,附加所有可能的下一步移动并将结果放回集合中(实际上,如果您想要,您可以迭代地而不是递归地执行此操作)
Level 1 generates 0,1,2,...
Level 2 removes 0 and replaces it with 00,01,02,...
Level 2 removes 1 and replaces it with 10,11,12,...
etc
答案 2 :(得分:0)
FIFO队列可能是比递归更好的方法,正如维基百科关于广度优先搜索的文章所建议的那样:http://en.wikipedia.org/wiki/Breadth_first_search。
我在C#中的解决方案:
string SolveRubiks()
{
string[] singleMoves = {"0","1","2"};
Queue<string> queue = new Queue<string>(singleMoves);
while (true)
{
string moveSequence = queue.Dequeue();
if (isSolution(moveSequence))
{
return moveSequence;
}
foreach (string singleMove in singleMoves)
{
queue.Enqueue(moveSequence + singleMove);
}
}
}
如果你需要一个迭代器,你可以将if块与yield return交换并更改方法签名,在Java中我想你必须实现一个迭代器接口(类似于Philip Uren的类)。
答案 3 :(得分:0)
我对Java库中的内容并不是很熟悉,如果这是实现已经存在的东西,那么道歉,但如果我从头开始编写这个,我可能会做这样的事情:
public class Enumerator {
private int maxDepth;
private int currentDepth;
private int currentPerm;
private String alphabet;
public Enumerator(String alphabet, int d) {
this.maxDepth = d;
this.currentDepth = 1;
this.currentPerm = 0;
this.alphabet = alphabet;
}
public boolean next() {
int numPermutations = (int) Math.pow(alphabet.length(), this.currentDepth);
boolean res=false;
// finished if
if ((this.currentDepth == this.maxDepth) &&
(this.currentPerm == numPermutations - 1)) {
res = false;
}
// next perm at this depth
else if (this.currentPerm < numPermutations - 1) {
this.currentPerm++;
res = true;
}
// next depth
else if (this.currentDepth <= this.maxDepth) {
this.currentDepth++;
this.currentPerm = 0;
res = true;
}
return res;
}
public String getPermutation() {
int tmpPerm = this.currentPerm;
String res = "";
for (int i=0; i<this.currentDepth; i++) {
int ind = tmpPerm % this.alphabet.length();
res = this.alphabet.charAt(ind) + res;
tmpPerm /= this.alphabet.length();
}
return res;
}
public static void main(String args[]) {
int depth = 3;
String alphabet = "012";
Enumerator e = new Enumerator(alphabet, depth);
do {
System.out.println(e.getPermutation());
} while (e.next());
}
}
这样,您可以枚举从任意符号的字母到任意深度的序列。这也可以满足您的需求,因为它可以在深度上进行迭代,并且每个深度都可以生成完整的可能序列集。 Gian说,它也可以用递归来完成,这可能更优雅。在Python中我会使用生成器函数,但我不熟悉Java中类似的东西。