java - 硬币 split 算法的性能

标签 java arrays performance recursion split

我的问题是一道CodeFu练习题(2012 round 2 problem 3)。它基本上归结为将整数数组分成两个(几乎)相等的两半并返回两者之间可能的最小差异。我在下面包含了问题描述。如评论中所述,这可以描述为 balanced partition problem ,这是 dynamic programming 领域的问题.

现在类似的问题已经讨论了很多,但是我找不到针对这个特定问题的有效解决方案。问题当然是要遍历的可能组合的数量很快就会变得对于蛮力搜索来说太大了(至少在使用递归时)。我有一个递归解决方案,它适用于除最大问题集以外的所有问题。我尝试添加一些优化来提前停止递归,但性能仍然太慢,无法在 CodeFu 允许的最大 5 秒内解决一些最大长度 (30) 的数组。非常欢迎任何关于如何改进或重写代码的建议。我也很想知道它是否有助于制作迭代版本。

更新: this fine site有一个关于平衡分区问题的理论讨论,它很好地说明了如何以动态方式着手解决这个问题。这确实是我所追求的,但我不知道如何准确地将理论付诸实践。电影中提到可以“使用反向指针的老把戏”找到两个子集合中的元素,但我看不出如何。

问题

You and your friend have a number of coins with various amounts. You need to split the coins in two groups so that the difference between those groups in minimal.

E.g. Coins of sizes 1,1,1,3,5,10,18 can be split as: 1,1,1,3,5 and 10,18 1,1,1,3,5,10 and 18 or 1,1,3,5,10 and 1,18 The third combination is favorable as in that case the difference between the groups is only 1. Constraints: coins will have between 2 and 30 elements inclusive each element of coins will be between 1 and 100000 inclusive

Return value: Minimal difference possible when coins are split into two groups

注意:CodeFu 规则规定在 CodeFu 服务器上的执行时间不得超过 5 秒。

主要代码

Arrays.sort(coins);

lower = Arrays.copyOfRange(coins, 0,coins.length-1);
//(after sorting) put the largest element in upper
upper = Arrays.copyOfRange(coins, coins.length-1,coins.length);            

smallestDifference = Math.abs(arraySum(upper) - arraySum(lower));
return findSmallestDifference(lower, upper, arraySum(lower), arraySum(upper), smallestDifference);

递归代码

private int findSmallestDifference (int[] lower, int[] upper, int lowerSum, int upperSum, int smallestDifference) {
    int[] newUpper = null, newLower = null;
    int currentDifference = Math.abs(upperSum-lowerSum);
    if (currentDifference < smallestDifference) {
        smallestDifference = currentDifference;
    } 
    if (lowerSum < upperSum || lower.length < upper.length || lower[0] > currentDifference 
            || lower[lower.length-1] > currentDifference 
            || lower[lower.length-1] < upper[0]/lower.length) {
        return smallestDifference;
    }
    for (int i = lower.length-1; i >= 0 && smallestDifference > 0; i--) {           
       newUpper = addElement(upper, lower[i]);
       newLower = removeElementAt(lower, i);
       smallestDifference = findSmallestDifference(newLower, newUpper, 
               lowerSum - lower[i], upperSum + lower [i], smallestDifference);
    }
    return smallestDifference;
}

数据集

这是一个求解时间过长的集合的示例。

{100000,60000,60000,60000,60000,60000,60000,60000,60000, 60000,60000,60000,60000,60000,60000,60000,60000,60000, 60000,60000,60000,60000,60000,60000,60000,60000,60000, 60000,60000,60000}

如果你想要完整的源代码,我已经把它放在Ideone 上了。 .

最佳答案

编辑 只是为了清楚:我已经在问题中指定了在五秒内运行的额外限制之前写了这个答案。我也写它只是为了表明有时蛮力是可能的,即使它看起来不是。所以这个答案并不意味着是这个问题的“最佳”答案:它恰恰是一个蛮力解决方案。作为一个附带的好处,这个小解决方案可以帮助某人编写另一个解决方案,以在可接受的时间内验证他们对“大型”数组的回答是否正确。

The problem is of course that the number of possible combinations to traverse soon grows too large for a brute force search.

鉴于最初陈述的问题(在指定最大运行时间 5 秒之前),我完全反对该陈述;)

你特意写了最大长度是30。

请注意,我不是在谈论其他解决方案(例如,动态编程解决方案,在您的约束条件下可能有效也可能无效)。

我说的是230 不大,10 亿多一点就够了。

现代 CPU 可以在一个内核上每秒执行数十亿个周期。

你不需要递归来解决这个问题:递归会破坏你的堆栈。有一种简单的方法可以确定所有可能的左/右组合:简单地从 0 计数到 2 exp 30 - 1 并检查每一位(决定,比如说,有点意味着你把值放在左边,关闭意味着你把右边的值)。

如果我没有记错的话,给出问题陈述,下面的方法应该可以工作,无需任何优化:

  public static void bruteForce( final int[] vals) {
    final int n = vals.length;
    final int pow = (int) Math.pow(2, n);
    int min = Integer.MAX_VALUE;
    int val = 0;
    for (int i = pow -1; i >= 0; i--) {
        int diff = 0;
        for ( int j = 0; j < n; j++ ) {
            diff += (i & (1<<j)) == 0 ? vals[j] : -vals[j];

        }
        if ( Math.abs(diff) < min ) {
            min = Math.abs(diff);
            val = i;
        }
    }

    // Some eye-candy now...
    for ( int i = 0 ; i < 2 ; i ++ ) {
        System.out.print( i == 0 ? "Left:" : "Right:");
        for (int j = 0; j < n; j++) {
            System.out.print(((val & (1 << j)) == (i == 0 ? 0 : (1<<j)) ? " " + vals[j] : ""));
        }
        System.out.println();
    }
}

例如:

bruteForce( new int[] {2,14,19,25,79,86,88,100});
Left: 2 14 25 79 86
Right: 19 88 100


bruteForce( new int[] {20,19,10,9,8,5,4,3});
Left: 20 19
Right: 10 9 8 5 4 3

在 30 个元素的数组上,在我便宜的 CPU 上它运行 125 秒。这是“初稿”,在单核上运行的完全未优化的解决方案(所述问题对于并行化来说是微不足道的)。

您当然可以变得更奇特,重用很多很多中间结果,从而在不到 125 秒的时间内解决一个包含 30 个元素的数组。

关于java - 硬币 split 算法的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13156894/

相关文章:

java - Amazon SNS 使用 Java 推送主题

相当于 C fscanf 的 Java

c++ - 将文本文件附加到 char 数组,接收垃圾输出

java - Hibernate 执行简单查询花费的时间太长

java - 在 Vector 的开头插入一个元素

java - 尝试在 Spring boot 应用程序中将行插入 H2 数据库时出现主键冲突异常

java - "VK_..."keyCodes 是方法还是对象?

Javadoc "ı" "i"问题

javascript - 根据在另一个具有不同属性的数组中的存在来过滤数组

c++ - 为什么我观察到多重继承比单一继承要快?