Question 2 Using the incomplete programming code given, complete the code using dynamic programming with memory function, to reproduce the results in the following Table 1. (C++)
Question 2
Using the incomplete
(C++)
#include<iostream>
using namespace std;
// max knapsack capacity // *** WRITE YOUR CODE HERE ***
// num of items // *** WRITE YOUR CODE HERE ***
// weight of each item // *** WRITE YOUR CODE HERE ***
// value of each item // *** WRITE YOUR CODE HERE ***
// variable for dynamic programming matrix // *** WRITE YOUR CODE HERE ***
//==========================================
// Dynamic programming function: recursive
// =========================================
//
// int value
// if F[i,j] is not filled yet (-1):
// (start with j = W, i = n)
// if capacity j < current item's weight w[i]:
// value = recall F(i-1, j)
// else:
// we can include current item,
// but check whether including or not including gives the maximum value
// value = max( F(i-1, j), itemValue[i] + F(i-1, j - itemWeight[i]));
// F[i,j] = value;
// return F[i,j]
// *** WRITE YOUR CODE HERE *** (OR INSIDE THE PSEUDOCODE ABOVE)
// *** WRITE YOUR CODE HERE *** (OR INSIDE THE PSEUDOCODE ABOVE)
int main(void){
int i; // item: 1 <= i <= n (row)
int j; // capacity: 1 <= j <= W (column)
// Initialization
// *** WRITE YOUR CODE HERE ***
// start from the goal F(n, W), then recursively calling dynamic programming function
//i = ??; *** WRITE YOUR CODE HERE ***
//j = ??; *** WRITE YOUR CODE HERE ***
cout << "\n Memory Function Knapsack \n";
cout << MFKnapsack(i,j) << endl;
// show the result
cout<<"\n----------------------------------------------"<<endl;
cout<<" Dynamic Programming List"<<endl;
cout<<"----------------------------------------------"<<endl;
for (i = 0; i <= n; i++){
for (j = 0; j <= W; j++){
cout << "F(" << i << "," << j << ") = " << F[i][j] << endl;
}
}
cout << endl;
cout<<"\n----------------------------------------------"<<endl;
cout<<" Dynamic Programming Matrix"<<endl;
cout<<"----------------------------------------------"<<endl;
for (i = 0; i <= n; i++){
for (j = 0; j <= W; j++){
cout<<F[i][j]<<"\t";
}
cout<<endl;
}
return 0;
}
Step by step
Solved in 2 steps