简体   繁体   中英

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}

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

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}

Note that this includes 0 , which is technically adding none of the elements together

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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