简体   繁体   English

所有数字均由数组元素相加得出

[英]All numbers resulting from adding elements of an array

I'm trying to make a program that, given an array of integers, returns all the values resulting from adding vector elements. 我正在尝试制作一个给定整数数组的程序,该程序返回所有添加矢量元素后得到的值。

For example: for a array A={2,1,3} the output should be {2,3,5,1,3,4,3,5,4,6} 例如:对于数组A = {2,1,3},输出应为{2,3,5,1,3,4,3,5,4,6}

I need to program it iteratively using brute force, I have tried to solve it using several nested for loops, but I have not had succes 我需要使用蛮力进行迭代编程,我尝试使用多个嵌套的for循环来解决它,但是我没有成功

I would recommend a recursive solution 我会推荐一个递归的解决方案

List<Integer> combos(int[] input)
{
    return combos(input, 0);
}

List<Integer> combos(int[] input, int offset)
{
    if(offset >= input.length) //base case, return 0 for no elements added
    {
        List<Integer> out = new ArrayList<Integer>((int)Math.pow(2, input.length));
        out.add(0);
        return out;
    }

    List<Integer> prev = combos(input, offset + 1);
    prev.addAll(prev); //double the previous result

    //add input[offset] to half the elements
    for(int i = 0; i < prev.size() / 2; i++)
        prev.set(i, prev.get(i) + input[offset]);

    return prev;
}

Inputting {1, 2, 4} outputs {7, 3, 5, 1, 6, 2, 4, 0} 输入{1, 2, 4}输出{7, 3, 5, 1, 6, 2, 4, 0} 7,3,5,1,6,2,4,0 {7, 3, 5, 1, 6, 2, 4, 0}

Note that this includes 0 , which is technically adding none of the elements together 请注意,这包括0 ,从技术上讲,这两个元素都不相加

Obviously since the output size will be 2^n , where n is the number of elements in input vector, this will run out of memory pretty soon. 显然,由于输出大小将为2^n ,其中n是输入向量中的元素数,因此这将很快耗尽内存。

That said, you're looking for the sum of all combinations of elements in the vector. 也就是说,您正在寻找向量中所有元素组合的总和。 So all you have to do is find all the combinations. 因此,您要做的就是找到所有组合。 One easy way to do that is to iterate from 0 to 2^n and in each iteration select only the indices from the vector for which bits in the iteration counter are turned on. 一种简单的方法是从0 to 2^n迭代0 to 2^n并且在每次迭代中仅从向量中选择索引,在该索引中为其打开了迭代计数器中的位。

Here's a brute force method 这是蛮力方法

package com.test;

import java.util.Arrays;

public class TestCombo {
    public static void main(String[] args) {
        int[] arr = {2, 1, 3};

        int resultCount = (int)Math.pow(2, arr.length);
        int[] result = new int[resultCount - 1];

        for(int i = 1; i < result.length + 1; i++) {
            int j = i;

            int sum = 0;

            for(int arrI = 0; j != 0; arrI++) {
                if( (j & 1) == 1) { //Is arrI bit turned on?
                    sum += arr[arrI];
                }

                j = j >> 1;
            }

            result[i-1] = sum;
        }

        Arrays.stream(result).forEach(System.out::println);;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM