Question

In: Computer Science

Print all subset sums of a given array recursively and iteratively. ex) if the input is...

Print all subset sums of a given array recursively and iteratively.

ex) if the input is {1, 2, 3}, it should return {0,1,2,3,3,4,5,6}.

public int[] subsetSum1(int[] arr) { *recursive*}

public int[] subsetSum2(int[] arr) {*iterative*}

Solutions

Expert Solution

A. Recursive Approach to print all subset sums of a given array -

//Global variable to keep track of the current index of the result array
int index;

void subsetSumRecursive(int[] arr, int left, int right, int sum, int[] result) {    
    // Add the sum of the current subset to the result array
    if (left > right) { 
        result[index] = sum;
        index++;
        return; 
    } 
      
    // Subset that includes arr[left] 
    subsetSumRecursive(arr, left + 1, right, sum + arr[left], result); 
      
    // Subset that excludes arr[left] 
    subsetSumRecursive(arr, left + 1, right, sum, result); 
} 

public int[] subsetSum1 (int[] arr) {
    //Initialize necessary variables
    index = 0;
    int left = 0;
    int right = arr.length-1;
    int sum = 0;
    int index = 0;
    int[] result = new int[1000];

    //call the recursive method
    subsetSumRecursive(arr, left, right, sum, result);

    return result;
}

B. Iterative Approach to print all subset sums of a given array -

public int[] subsetSum2(int[] arr)  {  
    int n = arr.length;
    int[] result = new result[1000];
    int index = 0;

    // There are total 2^n subsets  possible
    int total = 1 << n;  
  
    // Considering all numbers from 0 to 2^n - 1  
    for(int i = 0; i < total; i++)  {  
       int sum = 0;  
         
       // Consider the binary form of the current number for deciding which of the array elements to select  
       for(int j = 0; j < n; j++)  
          if ((i & (1 << j)) != 0)  
              sum += arr[j];  
         
       // Add the sum of the selected elements to the result array 
       result[index] = sum;
       index++;
    }  

    return result;
}  
 

Related Solutions

Given a 2D array a, sum up ALL the edges of the array. Ex. int a[...
Given a 2D array a, sum up ALL the edges of the array. Ex. int a[ ][ ] = { {1, 2, 3, 4},                        {5, 6, 7, 8},                        {9, 10, 11, 12} }; OUTPUT: Sum of the edges = 65
Problem Definition: Problem: Given an array of integers print all pairs of integers a and b...
Problem Definition: Problem: Given an array of integers print all pairs of integers a and b where a + b is equal to a given number. For example, consider the following array and suppose we want to find all pairs of integers a and b where a + b = 16 A= [ 10, 4, 6, 15, 3, 5, 1, 13] The following are pairs that sum to 16: 13, 3 6, 10 15, 1 Your program should print these...
. As input you are given two arrays: an array of numbers ? and an array...
. As input you are given two arrays: an array of numbers ? and an array ? of queries where each query is a target number. The array ? is unsorted and may contain duplicates. Your goal is, for each query ? in the array ?, count the number of pairs in the array ? that sums up to ?; that is, the number of distinct pairs of indices [?, ?], with ? < ?, such that ?[?] + ?[?]...
Complete the given C++ program (prob1.cpp) to read an array of integers, print the array, and...
Complete the given C++ program (prob1.cpp) to read an array of integers, print the array, and then find the index of the largest element in the array. You are to write two functions, printArray() and getIndexLargest(), which are called from the main function. printArray() outputs integers to std::cout with a space in between numbers and a newline at the end. getIndexLargest () returns the index of the largest element in the array. Recall that indexes start at 0. If there...
1a .Write a program that perform insertion sort (ascending order) on an input array and print...
1a .Write a program that perform insertion sort (ascending order) on an input array and print the total number of comparisons that have been made. You can implement by using any programming languages such as C/C++. For example, in the case of array B = [ 30 , 10 , 20 , 40 ], there are 4 needed comparisons to perform insertion sort (30 vs 10, 20 vs 30, 20 vs 10, and 40 vs 30). 1b. Write a program...
(a) Implement the following algorithm, which is given a duplicate-free array array as input, in C++....
(a) Implement the following algorithm, which is given a duplicate-free array array as input, in C++. whatDoIDo (array): 1) Build a heap from array (using buildHeap as explained in class), where the heap starts at position array[0]. 2) Starting from j = size of array - 1, as long as j>0: i. Swap the entries array[0] and array[j]. ii. Percolate down array[0], but only within the subarray array[0..j-1]. iii. Decrement j by 1. Provide three input/output examples for duplicate-free arrays...
How to print the element in the fifth row and seventh column given this array declaration...
How to print the element in the fifth row and seventh column given this array declaration in dev c: int hello[5][10];
Question 2. The following code defines an array size that sums elements of the defined array...
Question 2. The following code defines an array size that sums elements of the defined array through the loop. Analyze the following code, and demonstrate the type of error if found? What we can do to make this code function correctly? #include <stdio.h> #define A 10 int main(int argc, char** argv) { int Total = 0; int numbers[A]; for (int i=0; i < A; i++) numbers[i] = i+1; int i =0; while (i<=A){    Total += numbers[i];    i++; }...
Sum all the elements in the two-dimensional array below. Print the // result to the console....
Sum all the elements in the two-dimensional array below. Print the // result to the console. var arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] javascript
Print "Censored" if userInput contains the word "darn", else print userInput. End with newline. Ex: If...
Print "Censored" if userInput contains the word "darn", else print userInput. End with newline. Ex: If userInput is "That darn cat.", then output is: Censored Ex: If userInput is "Dang, that was scary!", then output is: Dang, that was scary! Note: If the submitted code has an out-of-range access, the system will stop running the code after a few seconds, and report "Program end never reached." The system doesn't print the test case that caused the reported message. #include <iostream>...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT