我的Havel-Hakimi算法代码有什么问题?

时间:2019-06-29 21:24:13

标签: java algorithm

我正在尝试练习自己的编码技能,我发现在Dailyprogrammer Reddit上使用了Havel-Hakimi算法(https://www.reddit.com/r/dailyprogrammer/comments/bqy1cf/20190520_challenge_378_easy_the_havelhakimi/)进行编码的做法,但是它总是返回错误的布尔值。

我试图在每个循环中检查我的进程,以确保所有方法都在执行正确的工作,并且输出是我期望的,但是它始终返回错误的布尔值。

public static void main(String[] args) {
    int[] answer = {16, 9, 9, 15, 9, 7, 9, 11, 17, 11, 4, 9, 12, 14, 14, 12, 17, 0, 3, 16};
    System.out.println(hh(answer));
    ArrayList<Integer> temp = new ArrayList<Integer>();
    System.out.println(temp.size());
}

//This is the actual Havel-Hakimi Algorithm Method
public static boolean hh(int[] answer) {
    ArrayList<Integer> temp = new ArrayList<Integer>();
    int n;
    for(int i = 0; i < answer.length; i++) {
        temp.add(answer[i]);
    }
    for(int j = 0; j < temp.size(); j++) {
        if(temp.get(j) == 0)
            temp.remove(j);
    }

    if(temp.size() == 0) {
        return true;
    }
    Collections.sort(temp);
    for(int t = 0; t < temp.size(); t++) {
    }
    n = temp.get(0);
    temp.remove(0);
    if(n > temp.size()) {
        return false;
    }
    for(int k = 0; k < n; k++) {
        temp.set(k, temp.get(k) - 1);
    }
    int[] newAnswer = new int[temp.size()];;
    for(int l = 0; l < temp.size(); l++) {
        newAnswer[l] = temp.get(l);
    }
    return hh(newAnswer);

}

使用main方法中提供的数组,“ hh”方法应返回true,但返回false。

1 个答案:

答案 0 :(得分:2)

问题出在Collections.sort(temp)上,它以升序对输入集合进行排序,而您希望它以降序进行排序。您可以使用Collections.sort(temp, Collections.reverseOrder())

这是代码中的逻辑问题。

我应该指出,某些语句在您的代码中是不必要的(例如for之后的Collections.sort(temp)循环,它什么也不做),其他语句可以得到增强(例如前两个{ {1}}循环,而不是复制整个数组,然后过滤它,为什么不只复制所需的元素呢?),您也可以通过使用for循环来避免使用递归。

以下代码可帮助您解决问题:

while(true)

如果您不熟悉public static void main(String[] args) { int[] answer = {16, 9, 9, 15, 9, 7, 9, 11, 17, 11, 4, 9, 12, 14, 14, 12, 17, 0, 3, 16}; System.out.println(hh(answer)); } //This is the actual Havel-Hakimi Algorithm Method public static boolean hh(int[] answer) { while(true) { // Filter zero's from answer array ArrayList<Integer> temp = new ArrayList(Arrays // get a Stream<Integer> from int[] .stream(answer) // filter zero's (this returns an IntStream) .filter(a -> a != 0) // reconvert it to Stream<Integer> .boxed() // Collect the stream as a List<Integer> .collect(Collectors.toList())); // Check the filtered array if it became empty after filtering if (temp.isEmpty()) { return true; } // Sort the filtered array in descending order Collections.sort(temp, Collections.reverseOrder()); // Remove the first element (note that remove method returns the removed element) int n = temp.remove(0); // Check if the first removed element is larger than the new size of the array if (n > temp.size()) { return false; } // Reconstruct the input array for the next iteration answer = IntStream.range(0, temp.size()) .map(i -> i < n ? temp.get(i) - 1 : temp.get(i)) .toArray(); } } ,可以直接使用Streams循环。

相关问题