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]));
}
defdefines a function. It's a little odd here that they're defining a function within another function, but that just scopes it. The rest of the syntax is very C-like, without the brackets of course. In python, the indentation defines what brackets would in C.min_coinsto access theVvariable from its parent namespace. I expect you could replace that with a third parameter tomin_coinsinstead.int* Vargument tomin_coins()and passV's length tomin_change(). You could useunsignedtype as a return value (number of ways is >=0), useUINT_MAXinstead offloat('inf')in this case.