Pastx
Pastx

Reputation: 767

Python to C algorithm

I am trying to find simple recursive implementation of change-making algorithm and all i could find is this (working) algorithm in python:

def min_change(V, C):
    def min_coins(i, aC):
        if aC == 0:
            return 0
        elif i == -1 or aC < 0:
            return float('inf')
        else:
            return min(min_coins(i-1, aC), 1 + min_coins(i, aC-V[i]))
    return min_coins(len(V)-1, C)

I dont understand python so i am asking for help if anyone could rewrite this small code in C or Java so it would be understandable to me. Or if anyone know of any implementation of this in C or Java can you post link please ?

Thank you for any help

edit: I was able to do this:

int min_change(int * V, int C) {
    return min_coins(/*Length-last index*/, C)
}

int min_coins(int i, int C) {
    if (C == 0)return 0;
    else if (i == -1 || C < 0)return sizeof (int)*32;
    else return min(min_coins(i - 1, C), 1 + min_coins(i, C - V[i]));
}

Upvotes: 1

Views: 224

Answers (1)

alexgirao
alexgirao

Reputation: 895

I believe this is the correct equivalent:

    #include <stdlib.h>
    #include <stdio.h>
    #include <stdint.h>

    int min_change0(int *V, int i, int aC)
    {
      if (aC == 0) {
        return 0;
      } else if (i == -1 || aC < 0) {
        return INT32_MAX - 1;
      } else {
        int a = min_change0(V, i-1, aC);
        int b = 1 + min_change0(V, i, aC - V[i]);
        return a <= b ? a : b;
      }
    }

    int min_change(int *V, int C)
    {
      int len = 0;
      while (V[len]) len++;
      /* min_coins(len(V)-1, C) */
      return len ? min_change0(V, len-1, C) : -1;
    }

    int main(void)
    {
      int total = 123;
      int values[] = {1,5,10,25,50,0 /* sentinel */};
      printf("minimal number of coins to change %i with 1, 5, 10, 25 and 50 coins is %i\n",
             total,
             min_change(values, total)
             );
      return 0;
    }

as 2*50 + 2*10 + 3*1 is 123

Upvotes: 1

Related Questions