我写了一个小程序,试图找到两个长度相等的英语单词之间的联系。单词 A 将通过一次更改一个字母来转换为单词 B,每个新创建的单词都必须是一个英文单词。
例如:
Word A = BANG
Word B = DUST
结果:
BANG -> BUNG ->BUNT -> DUNT -> DUST
我的过程:
将英文单词表(由 109582 个单词组成)加载到 a
Map<Integer, List<String>> _wordMap = new HashMap();
中,key 将是单词长度。用户输入 2 个字。
createGraph 创建一个图。
计算这两个节点之间的最短路径
打印出结果。
一切正常,但我对第 3 步所花费的时间不满意。
看:
Completely loaded 109582 words!
CreateMap took: 30 milsecs
CreateGraph took: 17417 milsecs
(HOISE : HORSE)
(HOISE : POISE)
(POISE : PRISE)
(ARISE : PRISE)
(ANISE : ARISE)
(ANILE : ANISE)
(ANILE : ANKLE)
The wholething took: 17866 milsecs
我对在步骤 3中创建图表所花费的时间不满意,这是我的代码(我使用 JgraphT 作为图表):
private List<String> _wordList = new ArrayList(); // list of all 109582 English words
private Map<Integer, List<String>> _wordMap = new HashMap(); // Map grouping all the words by their length()
private UndirectedGraph<String, DefaultEdge> _wordGraph =
new SimpleGraph<String, DefaultEdge>(DefaultEdge.class); // Graph used to calculate the shortest path from one node to the other.
private void createGraph(int wordLength){
long before = System.currentTimeMillis();
List<String> words = _wordMap.get(wordLength);
for(String word:words){
_wordGraph.addVertex(word); // adds a node
for(String wordToTest : _wordList){
if (isSimilar(word, wordToTest)) {
_wordGraph.addVertex(wordToTest); // adds another node
_wordGraph.addEdge(word, wordToTest); // connecting 2 nodes if they are one letter off from eachother
}
}
}
System.out.println("CreateGraph took: " + (System.currentTimeMillis() - before)+ " milsecs");
}
private boolean isSimilar(String wordA, String wordB) {
if(wordA.length() != wordB.length()){
return false;
}
int matchingLetters = 0;
if (wordA.equalsIgnoreCase(wordB)) {
return false;
}
for (int i = 0; i < wordA.length(); i++) {
if (wordA.charAt(i) == wordB.charAt(i)) {
matchingLetters++;
}
}
if (matchingLetters == wordA.length() - 1) {
return true;
}
return false;
}
我的问题:
如何改进我的算法以加快流程?
对于正在阅读本文的任何 redditors,是的,我在昨天看到 /r/askreddit 的线程后创建了这个。