I am new to dynamic programming and trying to solve an evergreen problem: cutting rod. I have been trying for hours and I am stuck. I am trying to debug it but without success. Here is my code
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int length = 5;
int peaces[2][4] = {{1, 2, 3, 4}, {2, 5, 7, 8}};
/*
length 1, 2, 3, 4
value: 2, 5, 7, 8
*/
//create working matrix: number of lengths X lengths
int work[4][6];
//fill in the first column with zeros
for( int k = 0; k < 5; k++ )
{
work[k][0] = 0;
}
//fill in the first row with zeroes
for( int k = 0; k <= length; k++ )
{
work[0][k] = 0;
}
for( int i = 1; i < 5; i++ ) // number of lengths
{
cout << endl << " i: " << i << " " << endl;
for( int j = 1; j < 6; j++ )
{
cout << endl << " j: " << j << " " << endl;
if( j >= i )
{
work[i][j] = max( work[i - 1][j], work[i][j - i] + peaces[1][i-1] );
}
else
{
work[i][j] = work[i - 1][j];
}
cout << endl;<< "inserted:" << work[i][j]<< endl;
for( int i = 0; i < 5; i++ )
{
for( int j = 0; j < 6; j++ )
{
cout << work[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
}
for( int i = 0; i < 5; i++ )
{
for( int j = 0; j < 6; j++ )
{
cout << work[i][j] << " ";
}
cout << endl;
}
return 0;
};
Something very strange happens and I can't figure out why: in the last iteration of the for loop I get right solution, but when exit the loop and I print the 2D array, it is changed, not the same as the one in the last iteration. Between two printing no operation is done on the array. I know that this is not an optimized solution, but that is the first one I have come up with. Question: Why is not the array filled the right way? What have I done wrong?