我有以下功能:
public ArrayList<ArrayList<Word>> createSentences(ArrayList<ArrayList<Word>> gestures, int startIndex) {
if (gestures.size() == 1) {
return gestures;
}
ArrayList<Word> ret;
ArrayList<ArrayList<Word>> result = new ArrayList<ArrayList<Word>>();
ArrayList<Word> tmp1 = gestures.get(0);
gestures.remove(0);
ArrayList<ArrayList<Word>> tmp2 = createSentences(gestures, startIndex + 1);
for (Word s : tmp1) {
for (Word s2 : tmp2.get(0)) {
ret = new ArrayList<Word>();
ret.add(s);
ret.add(s2);
result.add(ret);
}
}
return result;
}
给定输入:
ArrayList<ArrayList<Word>> test= new ArrayList<ArrayList<Word>>();
ArrayList<Word> gest1 = new ArrayList<Word>();
gest1.add(new Word("A", "N"));
gest1.add(new Word("B", "V"));
ArrayList<Word> gest2 = new ArrayList<Word>();
gest2.add(new Word("C", "N"));
gest2.add(new Word("D", "V"));
test.add(gest1);
test.add(gest2);
它产生以下结果:
[A, C]
[A, D]
[B, C]
[B, D]
这很好,但给定一个输入:
ArrayList<ArrayList<Word>> test= new ArrayList<ArrayList<Word>>();
ArrayList<Word> gest1 = new ArrayList<Word>();
gest1.add(new Word("A", "N"));
gest1.add(new Word("B", "V"));
ArrayList<Word> gest2 = new ArrayList<Word>();
gest2.add(new Word("C", "N"));
gest2.add(new Word("D", "V"));
ArrayList<Word> gest3 = new ArrayList<Word>();
gest3.add(new Word("E", "N"));
gest3.add(new Word("F", "V"));
test.add(gest1);
test.add(gest2);
test.add(gest3);
它产生:
[A, C]
[A, E]
[B, C]
[B, E]
我想实现所有可能的匹配组合,如下所示:
[A, C, E]
[A, C, F]
[A, D, E]
[A, D, F]
[B, C, E]
[B, C, F]
[B, D, E]
[B, D, F]
有人可以帮助我重写该函数以产生想要的结果吗?
最佳答案
在已经存在的两个循环中嵌套另一个循环。
或者使用适用于任意数量的输入单词列表的递归算法。
[编辑]
为了让您更容易理解正在发生的事情,这里有一些建议:
创建新类型,例如
class WordList extends ArrayList<Word> {}
和class Sentence extends ArrayList<Word> {}
这有助于明确你想要什么。代码将更具可读性。向新类型添加辅助方法。例如,添加
List<Sentence> appendWords( WordList )
至Sentence
从原始句子创建新句子,每个句子都附加单词列表中的一个单词。这使您可以保持代码简单:每个方法只做一件事。
这使您可以使最终算法变得非常简单:
List<Sentence> result = new ArrayList<Sentence>();
result.add( new Sentence() ); // start with an empty sentence
for( WordList words : wordLists ) {
List<Sentence> tmp = new ArrayList<Sentence>();
for( Sentence s : result ) {
tmp.addAll( s.appendWords( words ) );
}
result = tmp;
}
对于主循环的每次迭代,下一个单词列表中的所有单词都会附加到所有先前的结果中。
关于java - 造句功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7243043/