gpt4 book ai didi

java - 关于以下 Java 代码是否可以应用 DRY 的建议

转载 作者:行者123 更新时间:2023-12-02 01:47:36 25 4
gpt4 key购买 nike

public static HashMap<Language, Double> getBigramResult(ArrayList<Character> textCharList) {
HashMap<Language, Double> totalProbabilities = new HashMap<Language, Double>();
for (int j = 0; j < textCharList.size() - 1; j++) {
if (textCharList.get(j) != '+' && textCharList.get(j + 1) != '+') {
FileHandler.writeSentences("BIGRAM :"+textCharList.get(j)+""+textCharList.get(j + 1));
for (int k = 0; k < biGramList.size(); k++) {
BiGramV2 temp = biGramList.get(k);
double conditionalProbability = Math.log10(temp.getConditionalProbabilty(textCharList.get(j),
textCharList.get(j + 1)));
updateTotalProbabilities(totalProbabilities,temp.getLanguage(),conditionalProbability);
FileHandler.writeSentences(temp.getLanguage().toString()+ ": p("+textCharList.get(j+1)+"|"+textCharList.get(j) +") ="+conditionalProbability+"==> log prob of sentence so far: " +totalProbabilities.get(temp.getLanguage()));
}
FileHandler.writeSentences("");
}
}
return totalProbabilities;
}

public static HashMap<Language, Double> getUnigramResult(ArrayList<Character> textCharList) {
HashMap<Language, Double> totalProbabilities = new HashMap<Language, Double>();
for (int j = 0; j < textCharList.size(); j++) {
if (textCharList.get(j) != '+') {
FileHandler.writeSentences("UNIGRAM :"+textCharList.get(j));
for (int k = 0; k < uniGramList.size(); k++) {
Unigram temp = uniGramList.get(k);
double conditionalProbability = Math.log10(temp.getProbabilty(textCharList.get(j)));
updateTotalProbabilities(totalProbabilities,temp.getLanguage(),conditionalProbability);
FileHandler.writeSentences(temp.getLanguage().toString()+ ": p("+textCharList.get(j)+") ="+conditionalProbability+"==> log prob of sentence so far: " +totalProbabilities.get(temp.getLanguage()));

}
FileHandler.writeSentences("");
}
}
return totalProbabilities;
}

public static void updateTotalProbabilities(HashMap<Language, Double> totalProbabilities,Language l,double conditionalProbability)
{

Double oldValue = totalProbabilities.get( l);
totalProbabilities.put( l,oldValue != null ? oldValue + conditionalProbability : conditionalProbability);

}

在上面的代码中 ArrayList textCharList => 小写字符列表,包括“+”。

BiGramList 是“BiGramV2”类的列表,它有 2 个方法“getLanguage()”,返回德语、英语或法语(作为枚举),以及“getConditionalProbabilty()”,它接受 2 个字符并返回 double 值。

现在几乎相似的是 UniGramList 是 UniGram 类的列表,有 2 个方法“getLangauge()”(与 Bigram 相同)和“getProbabilty()”(接受 1 个字符并返回 double 值)。

以上两种方法非常相似,我觉得设计效率不高,但由于外层for循环、if block 不同以及概率计算方法不同,我无法重构它们。对我的代码的任何建议将不胜感激。

最佳答案

您可能想看看 strategy pattern .

关于java - 关于以下 Java 代码是否可以应用 DRY 的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53535509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com