【问题标题】:Making my dictionary search more efficient让我的字典搜索更高效
【发布时间】:2013-03-08 02:20:02
【问题描述】:

我在 Java 中创建了一个 boggle 求解器,它需要大约 1 分 30 秒来求解一个棋盘,我确信它是因为我遍历字典的方式。这个想法是它检查它是否是一个单词,并查看它是否是一个有效的前缀。如果它是一个有效的前缀,它将返回 true 以便程序继续运行。如果它返回 false,那么程序将停止运行它正在学习的课程。我阅读了有关 trie 结构的信息,但我不太了解如何实现它们。带有书面代码的示例,一个小的解释将不胜感激

private ArrayList <String> dic = new ArrayList<String>(/*dictionary()*/);//my useable dictionary
private ArrayList <String> dicFinal = new ArrayList<String>();//all the words found
private ArrayList <String> checked = new ArrayList<String>();//all words that have   already been checked go here
public boolean CheckTest (String word)throws IOException{//if its impossible to create a word with the combination of letters then it returns false, 
    String backw=reverse(word);
    boolean isValid = true;     
    if (word.length()<=1){isValid = true;}
    else if (checked.contains(word)&&checked.contains(backw)){}
    else{
        boolean isWord=true;
        if(checked.contains(word)){}
        else if(dic.contains(word)==true){
            setCount(getCount()+1);
            dicFinal.add(word);
            dic.remove(word);
            isWord=true;
        }
        else
            isWord=false;
        if(checked.contains(backw)==true){}
        else if (dic.contains(backw)==true){
            setCount(getCount()+1);
            dicFinal.add(backw);
            dic.remove(word);
        }
        if(isWord==false){
            for(int i=0;i<dic.size();i++){
                if(word.length()<=dic.get(i).length()&&dic.get(i).substring(0, word.length()).equalsIgnoreCase(word.substring(0, word.length()))){
                    isValid=true;
                    i=dic.size();
                }
                else 
                    isValid=false;
            }
        }
    }
    checked.add(word);
    checked.add(backw);
    return isValid;
}

【问题讨论】:

  • 看看dicchecked 的声明会很有价值。此外,如果您可以显示一些执行配置文件时间以确认 a)该函数实际上占用了大部分执行时间,并且 b)该函数的哪些部分占用了大部分执行时间,这将对您有所帮助我们针对最有希望的优化领域。
  • 如果事实证明字典访问实际上是瓶颈,那么在 superliminal.com/sources/TrieMap.java.html 有一个 Java 中的 trie 实现。
  • 它们都是arrayLists,我也不知道如何显示执行配置文件时间,因为我对Java/编程相当陌生

标签: java dictionary search solver boggle


【解决方案1】:

我建议首先要做的是制作dicchecked HashSets 而不是ArrayLists,这将为您提供O(1) 访问时间而不是O(N)。如果您认为这些查找是关键瓶颈的假设是正确的,那么您的程序的性能应该会大大提高。

如果这还不足以改善问题,那么值得花几分钟时间学习如何分析 Java 程序,以便查明问题所在。

【讨论】:

  • 我尝试将它们全部设为哈希集,但我无法找到获取存储在哈希集中的字符串的方法。 ArrayList 有 .get() 方法,hashsets 有一个迭代器,但是当我使用它时,它每次都没有返回任何内容。有什么想法吗?
  • 如果您可以使用带有迭代器的 HashSet 显示一些简洁、自包含的代码,以显示它的行为不正确(最好将其作为一个单独的问题),我或其他人可能会能够帮助你。如果您正在寻找如何做的例子,这里有一个简短的例子:stackoverflow.com/questions/6235010/….
猜你喜欢
  • 2013-10-06
  • 1970-01-01
  • 2020-09-15
  • 2020-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-19
  • 1970-01-01
相关资源
最近更新 更多