Advertisement
Mr_kindle

targetSum.c

Dec 21st, 2022
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.09 KB | Source Code | 0 0
  1. /*
  2.     Name: targetsum.c
  3.     Copyright:
  4.     Author: Mr.Kindle
  5.     Date: 21-12-22 21:04
  6.     Description: This code print total number of ways the target sum can be found using the given 'n' coins of
  7.     different denimination.
  8.     e.g : One can make a sum of 15 using coins of 2,3,5 in 7 ways.
  9.     All the matrix (2 1-D matrix and 1 2-D matrix) are dynamically allocated.
  10.    
  11.     replit: https://replit.com/@PrajjwalTripat2/TargetSum#main.c
  12. */
  13.  
  14.  
  15.  
  16. #include <malloc.h>
  17. #include <stdio.h>
  18. #define MAX 30
  19.  
  20.  
  21.  
  22. int main(void) {
  23.   int n, t_sum;
  24.  
  25.   int i, j,col;
  26.   int *coin, *target;
  27.   int * dpmat;
  28.  
  29.   printf("Enter total number of coins of different denomination\n");
  30.   scanf("%d", &n);
  31.   coin = calloc(n, sizeof(int));
  32.   printf("\nPlease enter all different denomination of coins : ");
  33.   for (i = 0; i < n; i++) {
  34.     printf("\nEnter coin %d:  ", i + 1);
  35.     scanf("%d", &coin[i]);
  36.   }
  37.   printf("\nEnter target sum:  ");
  38.   scanf("%d", &t_sum);
  39.   target = calloc(t_sum + 1, sizeof(int));
  40.   for (i = 0; i <= t_sum; i++)
  41.     target[i] = i;
  42.    
  43. dpmat = calloc(n * (t_sum + 1), sizeof(int));
  44. col = t_sum + 1;
  45.  
  46.  
  47.   for (i = 0; i < n; i++) {
  48.     for (j = 0; j <= t_sum; j++) {
  49. /*for first row of dpmatrix*/
  50.       if (i == 0) {
  51.         if (target[j] % coin[i] == 0)//
  52.           dpmat[i * col + j] = 1;
  53.       } else if (coin[i] > target[j])//if value of coin greater than the target at column j
  54.         dpmat[i * col +j] = dpmat[(i-1) * col + j];
  55.       else {
  56.           /*using the technic exclude, upper value and include*/
  57.         dpmat[i * col + j] = dpmat[(i-1) * col + j] + dpmat[i * col + (target[j] - coin[i])];
  58.       }
  59.     }
  60.   }
  61. printf("\n\nFollowing is your dpmatrix: \n\n");
  62.   for (i = 0; i < n; i++) {
  63.     for (j = 0; j <= t_sum; j++) {
  64.       printf("%2d ", dpmat[i * col +j]);
  65.     }
  66.     printf("\n");
  67.   }
  68.   /*The last element of the dpmatrix is the answer hence printing the last element*/
  69.   /*Last element is the cross section of the last row and the last column*/
  70.   printf("\nTotal number of ways = %d",dpmat[(n - 1)* col + (t_sum)]);
  71.  free(coin);
  72.   free(target);
  73.   free(dpmat);
  74.   return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement