Java 字谜算法在100%的情况下都不起作用
这是我的字谜算法Java 字谜算法在100%的情况下都不起作用,java,algorithm,recursion,factorial,anagram,Java,Algorithm,Recursion,Factorial,Anagram,这是我的字谜算法 public static void anagram() { String word = JOptionPane.showInputDialog("Enter the word"); char[] wordArray = word.toCharArray(); ArrayList<Integer> noOfRL = new ArrayList<>(); int repeatedLetters = 1; for
public static void anagram() {
String word = JOptionPane.showInputDialog("Enter the word");
char[] wordArray = word.toCharArray();
ArrayList<Integer> noOfRL = new ArrayList<>();
int repeatedLetters = 1;
for (int i = 0; i < word.length(); i++) {
for (int k = i+1; k < word.length()-1; k++) {
if (wordArray[i] == wordArray[k]) {
repeatedLetters++;
wordArray[k] = (char) (i+k);
}
}
if (repeatedLetters != 1) {
noOfRL.add(repeatedLetters);
}
repeatedLetters = 1;
}
double totalCombinations = factorial(word.length());
double restrictions = 1;
for(int i = 0; i < noOfRL.size(); i++){
restrictions *= factorial(noOfRL.get(i));
}
double actualCombinations = totalCombinations/restrictions;
System.out.println(actualCombinations);
}
public static double factorial(double number) {
if (number > 1) {
return number * factorial(number - 1);
} else {
return 1;
}
}
publicstaticvoidanagram(){
String word=JOptionPane.showInputDialog(“输入单词”);
char[]wordArray=word.toCharArray();
ArrayList noOfRL=新的ArrayList();
int repeatedLetters=1;
for(int i=0;i1){
返回数*阶乘(数-1);
}否则{
返回1;
}
}
它适用于所有正常的单词。
但是,只要您输入eeeeeee或AAAAAAAA。等
代码未能给出正确答案1。
调试后,我意识到重复字母的数量总是比字符串长度少1,因此给出了错误的答案
如何解决这个问题?我认为,您的嵌套for循环是不必要的复杂。 您可以使用streams聚合相同的字母,并通过阶乘函数减小结果列表的大小。 结果可能如下所示:
public static void anagram() {
final String word = JOptionPane.showInputDialog("Enter the word");
final double restrictions = com.google.common.primitives.Chars
.asList(word.toCharArray())
.stream()
.collect(
collectingAndThen(
groupingBy(Function.identity()),
map -> map.values().stream()
.mapToDouble(List::size)
.filter(l -> l > 1)
.reduce(1, (a, b) -> a * factorial(b))));
final double totalCombinations = factorial(word.length());
final double actualCombinations = totalCombinations / restrictions;
System.out.println(actualCombinations);
}
我不明白你所说的
wordArray[k]=(char)(I+k)是什么意思
假设您发现k==25
位置的字符等于i==8
位置的字符,此赋值将用(char)(25+8)
字符替换单词数组[25]
字符,该字符是一个感叹号!'==33
。为什么?这可能会在以后产生额外的错误“重复字符”(例如,如果wordArray[17]
中有!”
)……我建议您只需对单词中的字符进行排序,然后扫描以找出重复字符。它们将被分组在一起,因此您可以通过比较相邻位置轻松地检测它们,并且可以通过扫描下一个不同的字符轻松地对它们进行计数。