【问题标题】:Anagram Algorithm does not work 100% of the timeAnagram 算法不能 100% 工作
【发布时间】:2015-06-08 10:23:09
【问题描述】:

这是我的字谜算法

   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;

    }
}

它适用于所有普通单词。 但是,只要您输入 eeeeeee 或 aaaaaaaaa。等等... 代码未能给出正确答案 1。 调试后发现重复字母的个数总是比字符串的长度少1,所以给出了错误的答案。

我该如何解决这个问题?

【问题讨论】:

  • 我无法理解你所说的wordArray[k] = (char) (i+k); 的意思假设你发现k==25 位置的字符等于i==8 位置的字符,这个赋值将用@987654326 替换wordArray[25] 字符@这是一个感叹号'!' == 33。为什么?这可能会在以后产生额外的错误“重复字符”(例如,如果 wordArray[17] 处有 '!')......
  • 我建议您对单词中的字符进行简单的排序,然后对其进行扫描以找出重复的字符。它们将被组合在一起,因此您可以通过比较相邻位置轻松检测它们,并且您可以通过扫描下一个不同字符轻松计数它们。

标签: java algorithm recursion factorial anagram


【解决方案1】:

我会说,您的嵌套 for 循环是不必要的复杂。 您可以使用流来聚合相同的字母并通过阶乘函数减小结果列表的大小。 结果可能如下所示:

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);
}

【讨论】:

    猜你喜欢
    • 2015-08-09
    • 2021-07-23
    • 2012-03-08
    • 2015-07-18
    • 2012-12-04
    • 2015-12-06
    • 2011-09-27
    • 2012-04-05
    • 1970-01-01
    相关资源
    最近更新 更多