fork download
  1. #include <stdio.h>
  2.  
  3. int count_combinations(
  4. int itemCosts[]
  5. , size_t costCount
  6. , int pickedItems[]
  7. , size_t pickedCount
  8. , size_t pickedTargetCount
  9. , size_t minIndex
  10. , int funds
  11. ) {
  12. if (pickedCount == pickedTargetCount) {
  13. // This is the base case. It has the code similar to
  14. // the "if" statement from your code, but the number of items
  15. // is not fixed.
  16. int sum = 0;
  17. for (size_t i = 0 ; i != pickedCount ; i++) {
  18. sum += pickedItems[i];
  19. }
  20. if (sum <= funds) {
  21. for (size_t i = 0 ; i != pickedCount ; i++) {
  22. printf("%d ", pickedItems[i]);
  23. }
  24. printf("\n");
  25. }
  26. // The following line will return 0 or 1,
  27. // depending on the result of the comparison.
  28. return sum <= funds;
  29. } else {
  30. // This is the recursive case. It is similar to one of your "for"
  31. // loops, but instead of setting "one", "two", or "three"
  32. // it sets pickedItems[0], pickedItems[1], etc.
  33. int res = 0;
  34. for (size_t i = minIndex ; i != costCount ; i++) {
  35. pickedItems[pickedCount] = itemCosts[i];
  36. res += count_combinations(
  37. itemCosts
  38. , costCount
  39. , pickedItems
  40. , pickedCount+1
  41. , pickedTargetCount
  42. , i+1
  43. , funds
  44. );
  45. }
  46. return res;
  47. }
  48. }
  49.  
  50.  
  51. int main(void) {
  52. int itemCosts[] = {1, 3, 5, 7}; // The costs
  53. int pickedItems[2]; // No need to initialize this array
  54. int res = count_combinations(itemCosts, 4, pickedItems, 0, 2, 0, 8);
  55. printf("Got %d combinations\n", res);
  56. return 0;
  57. }
  58.  
Success #stdin #stdout 0s 2112KB
stdin
Standard input is empty
stdout
1 3 
1 5 
1 7 
3 5 
Got 4 combinations