user6744717
user6744717

Reputation:

How can we find the sum for each subset of array

I am trying to finding the sum of each in the below code in java.What changes should i have to made in this code.

import java.io.IOException;

class as {

    static void printSubsets(int set[]) {
        int n = set.length;
        for (int i = 0; i < (1 << n); i++) {
            for (int j = 0; j < n; j++) {
                if ((i & (1 << j)) > 0) {
                    System.out.print(set[j] + " ");
                }
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int set[] = { 1, 2, 3 };
        printSubsets(set);
    }
}

Output of above code is:

1 
2     
1 2     
3     
1 3     
2 3     
1 2 3 

I want To Multiply each element of subset by its last number for e.g.

1*1=1    
2*2=4    
1*2+2*2=6    
3*3=9

likewise all elements 

and lastly generate sum of all these subset 1+4+6+9+.. and so on.

Above code also print null set and subset are in order.How this program can be edited to make changes such that it does'nt print null set and print random substring.

Upvotes: 0

Views: 288

Answers (1)

Nikolas
Nikolas

Reputation: 44398

As far as I understand your question, you want to multiply all the elements with each other and print out each step of iteration with the result. Here you are:

static void printSubsets(int set[]) {
    int sum = 0;
    for (int i=0; i<set.length; i++) {
        for (int j=i; j<set.length; j++) {
            int var = set[i] * set[j];
            sum += var;
            System.out.println("( " + set[i] + " * " + set[j] + " = " + var + " ) -> sum=" + sum);
        }
    }
    System.out.println("final sum=" + sum);
}

In case of input [1,2,3], the sum is supposed to grow according my algorithm by:

1, 3, 6, 10, 16 up to 20


Just a note about << shift operator which shifts a bit pattern to the left. Let's say that number 2 is understood as 10 in binary. Shifting this number by 2 << 4 will result 100000 in binary that is understood as 32 in decimal. I am not sure you really need this pattern.

Upvotes: 1

Related Questions