I'm making a program that takes a target value and a set list of values, I need to pick numbers from the list that will add up to the target value.
This all has to be done on the command line.
Im stuck on two parts:
First is I'm not 100% sure if I'm reading in all the values correctly. Because on some tests where there shouldn't be a match it says there is a match.
For example subset2 100 1 2 3 4 Combination Match Found
It should print out instead no match found cause 1,2,3,4 dont add up to 100. I've added my code to help you see what im doing
Second, I need to print out the numbers in the list that do match with the target value. How would I be able to do that, I'm stumped on how i could do this.
For example subset 9 1 2 4 5 {4,5}
#include <stdio.h>
#include <stdbool.h>
bool subset(int set[], int n, int sum);
int main(int argc, char *argv[])
{
int value = atoi(argv[1]);
// Error checking to see if the value is a negative
if (value <= 0) {
printf("Parameter 1 can not be negative\n");
return -1;
}
int k;
int t = 0;
for (k = 2; k < argc; k++) {
t++;
}
int i;
int array = 0;
/*
* Putting the elements from the command line in an array starting
* from the second element on the command line
*/
for (i = 2; i < t; i++) {
array += atoi(argv[i]);
}
int set[array];
int n = sizeof(set) / sizeof(set[0]);
// Call subset to check and see if there is a match
if (subset(set, n, value) == true) {
printf("Combination Match Found\n");
} else {
printf("No Combination Matches\n");
}
return 0;
}
// Returns true if there is a subset that equals the value
bool subset(int set[], int n, int sum)
{
// Base cases
if (sum == 0)
return true;
if (n == 0 && sum != 0)
return false;
// If last element is greater than sum, then its ignored
if (set[n - 1] > sum)
return (subset, n - 1, sum);
// Check if value can be found with or without last element
return subset(set, n - 1, sum) || subset(set, n - 1, sum - set[n - 1]);
}