Assignment 2: Testing a solution to a simplified Knapsack Problem. You have won
ID: 670885 • Letter: A
Question
Assignment 2:
Testing a solution to a simplified Knapsack Problem.
You have won a shopping spree. The rules are: you need to buy four items that cost in total at least x dollars but weigh at most y kg in total.
Let's say x = $50.00 and y = 20 kg, and my items are:
Poster $20 20 g
Bowling Ball $10 15 kg
Laptop $800 5 kg
Rug $15 2 kg
This will fail, although the value ($845) is greater than $50, the total weight is too much, at 22 kg 20 g.
If I were to exchange the laptop for:
Pen $2 10 g
I would still fail because while the weight (now 17 kg and 30 g) is acceptable, the value is now $47, which is too little.
However if I exchanged the bowling ball for the pen, I would now have a total weight of 7 kg 30 g, and a value of $837 which is acceptable.
You will need to handle the user inputting a weight either with grams (g) or with kilograms (kg). So user input for any weight value, including the maximum, should operate under the assumption
(number)(space)(unit)
for example
10 kg
or
400 g
Using these guidelines I must create a C++ program that will give me these outputs.
Explanation / Answer
#include <iostream>
#include <cmath>
#include <string>
#include <iomanip>
using namespace std;
int main() {
double Min_Dollar;
double Max_Weight;
double OneDV;
double OneW;
double TwoDV;
double TwoW;
double ThreeDV;
double ThreeW;
double FourDV;
double FourW;
double minprice;
double maxweight;
cout <<endl << "Enter Minimum Dollar Value:";
cin >> Min_Dollar;
cout <<endl << "Enter Maximum Weight:";
cin >> Max_Weight;
cout << "kg";
cout <<endl << "Enter Item One Dollar Value:";
cin >> OneDV;
cout <<endl << "Enter Item One Weight:";
cin >> OneW;
cout << " g";
cout <<endl << "Enter Item Two Dollar Value:";
cin >> TwoDV;
cout <<endl << "Enter Item Two Weight:";
cin >> TwoW;
cout << " g";
cout <<endl << "Enter Item Three Dollar Value:";
cin >> ThreeDV;
cout <<endl << "Enter Item Three Weight:";
cin >> ThreeW;
cout << " g";
cout <<endl << "Enter Item Four Dollar Value:";
cin >> FourDV;
cout <<endl << "Enter Item Four Weight:";
cin >> FourW;
cout <<endl;