given N absolute values of integers find the combination of N/2 negative and N/2 positive values whose sum is closest to 0

后端 未结 5 1465
隐瞒了意图╮
隐瞒了意图╮ 2021-01-21 04:36

Let\'s say that I have an array of 10 numbers whose absolute value range can go from 1 to 10. Values can be repeated. An example of this could be

{2, 4, 2, 6, 9         


        
5条回答
  •  灰色年华
    2021-01-21 04:59

    This is a java implementation of the algorithm described by amin k.

    It's less cool than the Haskell implementation, I have no formal proof that it works in every case, but it seems to be working.

    import java.util.Arrays;
    import java.util.Random;
    
    public class TestPermutations {
    
    int[] values = new int[10];
    int[] positives = new int[5];
    int[] negatives = new int[5];
    
    public static void main(String... args) {
        new TestPermutations();
    }
    
    public TestPermutations() {
        Random ra = new Random();
        System.out.println("generating sequence...");
        for (int i = 0; i < 10; i++) {
            values[i] = (ra.nextInt(10) + 1);
            System.out.print(values[i] + " ");
        }
        Arrays.sort(values);
    
        int sum = 0;
        int positiveIndex = 0;
        int negativeIndex = 0;
        for (int i = values.length - 1; i >= 0; i--) {
            if (i == values.length - 1) {
                negatives[negativeIndex] = - values[i];
                negativeIndex++;
                sum -= values[i];
            }
            else {
                if (sum <= 0) {
                    if (positiveIndex < 5) {
                        positives[positiveIndex] = values[i];
                        positiveIndex++;
                        sum += values[i];
                    }
                    else {
                        negatives[negativeIndex] = - values[i];
                        negativeIndex++;
                        sum -= values[i];
                    }
                }
                else {
                    if (negativeIndex < 5) {
                        negatives[negativeIndex] = - values[i];
                        negativeIndex++;
                        sum -= values[i];
                    }
                    else {
                        positives[positiveIndex] = values[i];
                        positiveIndex++;
                        sum += values[i];
                    }
                }
            }
        }
    
        System.out.print("\npositives ");
        for (int pos : positives) {
            System.out.print(pos + " ");
        }
        System.out.print("\nnegatives ");
        for (int neg : negatives) {
            System.out.print(neg + " ");
        }
        System.out.println("\nsum closest to 0: " + sum);
    }
    }
    

提交回复
热议问题