Skip to content

Instantly share code, notes, and snippets.

@samarthsewlani
Created April 24, 2024 10:32
Show Gist options
  • Save samarthsewlani/275fbd0eb7d999a5b0c83e39d086cf99 to your computer and use it in GitHub Desktop.
Save samarthsewlani/275fbd0eb7d999a5b0c83e39d086cf99 to your computer and use it in GitHub Desktop.
Sum Of Subsets in C
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX 100
int INFINITY = INT_MAX;
int X[MAX];
int compare(const void* num1, const void* num2) // comparing function
{
int a = *(int*) num1;
int b = *(int*) num2;
if(a > b) return 1;
else if(a < b) return -1;
return 0;
}
void printSolution(int n){
printf("X: ");
for(int i=0;i<n;i++) printf("%d ", X[i]);
printf("\n");
}
void sum_of_subset(int i, int n, int arr[], int target, int sum, int remSum){
X[i] = 1;
if(sum + arr[i] == target){
printSolution(n);
}
else if(sum + arr[i] + arr[i+1] <= target){
sum_of_subset(i+1, n, arr, target, sum + arr[i], remSum - arr[i]);
}
if(((sum + remSum - arr[i])>=target) && (sum + arr[i+1] <= target)){
X[i] = 0;
sum_of_subset(i+1, n, arr, target, sum, remSum - arr[i]);
}
}
int main() {
int n, arr[MAX], target, remSum = 0;
printf("Enter N: ");
scanf("%d", &n);
printf("Enter elements one by one: \n");
for(int i=0;i<n;i++) scanf("%d", &arr[i]);
printf("Enter target: \n");
scanf("%d", &target);
for(int i=0;i<n;i++) remSum+=arr[i];
//Sort the array if not already sorted
qsort(arr, n, sizeof(int), compare);
sum_of_subset(0, n, arr, target, 0, remSum);
return 0;
}
/*
5
3 5 6 8 10
16
7
3 5 6 8 10 12 13
16
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment