目標値と一連の値のリストを受け取るプログラムを作成しています。目標値に加算されるリストから数値を選択する必要があります。
これはすべてコマンドラインで行う必要があります。
私は2つの部分で立ち往生しています:
1 つ目は、すべての値を正しく読み込んでいるかどうか 100% 確信が持てないことです。一致するべきではない一部のテストでは、一致があると表示されるためです。
たとえば、subset2 100 1 2 3 4 組み合わせ一致が見つかりました
代わりに、1,2,3,4 の合計が 100 にならないため、一致が見つかりませんでした。何をしているかを確認できるようにコードを追加しました。
次に、ターゲット値と一致するリスト内の数値を出力する必要があります。どうすればそれができるのでしょうか、どうすればこれができるのか困っています。
たとえば、サブセット 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]);
}