Created
August 7, 2022 12:48
-
-
Save viraatmaurya/1cb21ec858ce72c318b9396ec1de3eac to your computer and use it in GitHub Desktop.
Best sum for coin change problem in C.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <stdbool.h> | |
#include <assert.h> | |
#define MAX_LEN 10 | |
size_t count = 0, i = 0; | |
void appendToArray(int *array, int len, int value); | |
int cmp(const void *a, const void *b); | |
int *cache(int n); | |
int canSum(int target, int numbers[], int len, int *memo, int *array); | |
int main(int argc, char const *argv[]) | |
{ | |
int *array = calloc(MAX_LEN, sizeof(int)); | |
assert(canSum(70, (int[]){10, 12, 5}, 3, cache(30), array)); | |
printf("Test 3: Passed\n"); | |
printf("["); | |
while (array[i] != 0) | |
{ | |
printf(" %d,", array[i]); | |
i++; | |
} | |
printf("]\n"); | |
free(array); | |
return 0; | |
} | |
int canSum(int target, int numbers[], int len, int *memo, int *array) | |
{ | |
qsort(numbers, len, sizeof(int), cmp); | |
if (memo[target] == target) | |
{ | |
return memo[target]; | |
} | |
int remainder = -1; | |
if (target == 0) | |
{ | |
return true; | |
} | |
if (target < 0) | |
{ | |
return false; | |
} | |
for (int i = 0; i < len; i++) | |
{ | |
/** | |
* *This is for debugging purpose. | |
*/ | |
// printf("Try [%d]:[%d - %d] = %d \n", i, target, numbers[i], target - numbers[i]); | |
remainder = target - numbers[i]; | |
if (remainder == 0) | |
{ | |
appendToArray(array, count, numbers[i]); | |
return true; | |
} | |
if (canSum(remainder, numbers, len, memo, array) == true) | |
{ | |
appendToArray(array, count, numbers[i]); | |
memo[target] = true; | |
return memo[target]; | |
} | |
} | |
memo[target] = false; | |
return memo[target]; | |
} | |
int *cache(int n) | |
{ | |
int *cache = (int *)malloc(sizeof(int) * n); | |
for (int i = 0; i < n; i++) | |
{ | |
cache[i] = -1; | |
} | |
return cache; | |
} | |
int cmp(const void *a, const void *b) | |
{ | |
const int *A = a, *B = b; | |
/* a>b => -1, a<b => 1, a==b => 0 */ | |
return (*A < *B) - (*A > *B); | |
} | |
void appendToArray(int *array, int len, int value) | |
{ | |
array[len] = value; | |
count += 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment