Click here to Skip to main content
15,879,184 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I not getting correct output for cut rod aux algorithm implementation, I am using visual studio 2010 for implementation of Memoized Cut rod aux function....

C++
int max_val=0;

int max(int a, int b)
    {
         return(a>b)?a:b;
    }
int cut_rod_aux(int, int, int);
int cut_rod(int, int);

Most probably error is in this section of code
C++
int cut_rod_aux(int price[], int n, int r[])
   {
        if(r[n]>=0)
          {
               return r[n];
                cout<<"aux r="<<r<<endl;
          }
        if (n==0)
          {
                max_val=0;
                cout<<"aux max val = 0"<<endl;
          }
        else
         {   /*most probably error area*/
              max_val = 0;
              for(int i=1; i<n;>
              {
                         max_val=max(max_val, price[i]+cut_rod_aux(price, n-i,r));
                         cout<<"aux max val: "<<max_val<<endl;
                  }
          }

       r[n]=max_val;
       return max_val;
   }
   int cut_rod(int price[], int n)
   {
        int *r = new int[n];
        for(int i=0; i<n;>                {
                r[i]=0;
                cout<<"i="<<i<<" r="<<r[i]<<endl;
            }
       return cut_rod_aux(price,n,r);
   }
   int _tmain(int argc, _TCHAR* argv[])
   {
          int arr[]={1, 5, 8, 9, 10, 17, 17, 20};
           cout<<"output "<<cut_rod(arr, 8)<<endl;
          /*output should be 22, as per coreman book*/
       return 0;
   }


What I have tried:

The correct output should be 22, instead it is giving 20...
Posted
Updated 24-Jan-23 20:56pm
v4

1 solution

You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]

This line is weird to say the least. piece of code missing ?
C#
for(int i=1; i<n;>
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900