I've been tasked with creating a brute force/exhaustive search to solve the 0-1 Knapsack problem. I have been give a sample file for input which is as follows:
3
4
5
2 1 3 2
12 10 20 15
5
6
3 2 1 4 5
25 20 15 40 50
6
10
3 2 1 5 5 6
10 10 12 10 12 12
The first number is the number of instances (3), then it follows the pattern of number of items, capacity of knapsack, weight of item, and value of item from line to line. In this code I have been told to implement the functions getInstance (reads data from the file and stores), putInstance (outputs the data to the screen), and solveInstance (analyzes the data to discover feasible subsets). The following is my current code:
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
// Knapsack functions ///////////////////////////////////
void getInstance (int & W, // Knapsack capacity
int & n, // number of items
int* & v, // values of items
int* & w) // weights of items
{
cin >> n;
cin >> W;
w = new int[n];
for (int i=0; i<n; i++) {
cin >> w[i];
v = new int[n];
for (int i=0; i<n; i++)
cin >> v[i];
}
void putInstance (int W, // Knapsack capacity
int n, // number of items
int * v, // values of items
int * w) // weights of items
{
cout << "There are " << n << " items." << endl;
cout << "The knapsack capacity is " << W << "." << endl;
for (int i = 0; i < n; i++) {
cout << "\t" << i << "\t";
}
cout << endl;
for (int i = 0; i < n; i++) {
cout << "w: \t" << w[i] << "\t";
}
cout << endl;
for (int i = 0; i < n; i++) {
cout << "v: \t" << v[i] << "\t";
}
cout << endl;
cout << "W = " << W;
}
void solveInstance (int W, // Knapsack capacity
int n, // number of items
int * v, // values of items
int * w) // weights of items
{
}
int main()
{
ifstream inFile;
inFile.open("PA2_data.txt");
if (!inFile.is_open()) {
cerr << "Can't find input file." << endl;
exit(1);
}
int nInsts; // number of problem instances
cin >> nInsts;
for (int i=1; i<= nInsts; i++)
{
int W; // Knapsack weight capacity
int n; // Number of items
int * v; // Values of items
int * w; // Weights of items
getInstance (W, n, v, w);
cout << "--------------------------------\n";
cout << "Problem instance #" << i << "\n";
putInstance (W, n, v, w);
solveInstance (W, n, v, w);
cout << endl;
int nFeasible = 0;
}
inFile.close();
}
The program is picking up the .txt file because the error is not appearing, however the rest of the program is blank.

New Topic/Question
This topic is locked



MultiQuote



|