Quote (Richter @ Dec 5 2012 05:14am)
You're right imo.
Thats somehow what I wanted to express with my statement, that there's no way a recursive solution could simplify the complexity of the problem domain.
You can only code a recursive solution, which evaluates the same possibilities as the nested loops.
I think you're misunderstanding the recursive solution if you think it's evaluating the same possibilities as the nested loops.
Unless I'm misreading your code (possible, but unlikely), you're doing a selective dictionary attack on the problem -- that is, try all possible combinations of change and keep the ones that get you the total amount that you want. Which means that although you can set upper and lower bounds to the total amount, you're still considering combinations that Just Don't Work. (i.e. some combinations get you $2 when you want $1.50)
Code
for(i=0; i*25<=amount; i++) {
for(j=0; j*10<=amount; j++) {
for(k=0; k*5<=amount; k++) {
for(l=0; l<=amount; l++) {
if (25*i + 10*j + 5*k + l == amount)
pos++, printf("%d %d %d %d\n",i,j,k,l);
}}}}
Notice that at the highest values of i, j, k, and l here, you are considering a combination that cannot
possibly be correct. In the if block, you are quite literally testing
Code
amount + amount + amount + amount == amount
at the end of the loop here.
The inductive solution explicitly does NOT do that or anything like it. Instead, it is a generator -- it generates all the possible combinations that satisfy the problem space to an exact amount, with no extra work being done or thrown away. At any given step of the process, the recursive solution is in the process of building a bona fide, 100% valid combination.
The fact that the recursive code creates duplicate copies of the same solutions is a fault of the code, not the solution (because from the perspective of readability and simplicity of expression, deduping is easier than implementing the inductive solution verbatim). It's worth noting that by definition, whatever extra work is done (i.e. generating duplicates) still results in generating
solutions that are valid and not invalid ones that you test and throw away.
Or here's another way to look at it. The recursive implementation is doing a full BFS over the solution itself (and sometimes revisiting the same node twice or more than twice). The iterative implementation is (generously speaking) doing a bounded BFS over the
solution space.
So you are either seriously misunderstanding the code you wrote for yourself, or you are seriously misunderstanding what the inductive/recursive solution actually does.
This post was edited by irimi on Dec 5 2012 01:46pm