Skip to content

Commit

Permalink
Added Knapsack Problem and Making a Change Problem! Both are solved i…
Browse files Browse the repository at this point in the history
…n C++.
  • Loading branch information
letscodedev committed Oct 12, 2019
1 parent 71346a4 commit 06b9b2d
Show file tree
Hide file tree
Showing 2 changed files with 123 additions and 0 deletions.
81 changes: 81 additions & 0 deletions greedy_algorithms/KnapSack.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
#include <iostream>
using namespace std;
float *w,*w1,*v,*v1,W, *v_w,*x;
int n;

int max_value(float* v_w)
{
float maxx=0;
int index;
for(int i=0;i<n;i++)
{
if(maxx < v_w[i] && x[i] == 0)
{
maxx = v_w[i];
index = i;
}
}

return index;
}

int main()
{
float value=0,weight = 0;
int index;
cout<<"Enter no. of weights: ";
cin>>n;

w = new float[n];
v = new float[n];
v_w = new float[n];
x = new float[n];

for(int i=0;i<n;i++)
{
x[i] = 0;
}
cout<<"Enter the Weights:\n";
for(int i=0; i<n;i++)
{
cin>>w[i];
}

cout<<"Enter the values:\n";
for(int i=0; i<n;i++)
{
cin>>v[i];
}
for(int i=0;i<n;i++)
{
v_w[i] = v[i] / w[i];
}
cout<<"Enter the knapsack Capacity: ";
cin>>W;

cout<<"The given data are:\n";
cout<<"w[]: ";
for(int i=0;i<n;i++)
cout<<w[i]<<" ";
cout<<"\nv[]: ";
for(int i=0;i<n;i++)
cout<<v[i]<<" ";
cout<<"\nv/w[]: ";
for(int i=0;i<n;i++)
cout<<v_w[i]<<" ";
while(weight<W){
index = max_value(v_w);
if(weight + w[index] <= W ) {
x[index] = 1;
weight = weight + w[index];
} else {
x[index] = (W - weight)/w[index];
weight = W;
}
}
cout<<"\nOutput:";
for(int i=0;i<n;i++){
cout<<x[i]<<" ";
}
return 0;
}
42 changes: 42 additions & 0 deletions greedy_algorithms/MakingChangeProblem.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#include <iostream>
using namespace std;
int main()
{
int n, N;
cout << "Enter the number of coins available: ";
cin >> n;
int * arr = new int[n];
cout << "Enter the values of coins.. \n";
for(int i=0; i<n; i++)
{
cin >> arr[i];
}
cout << "Enter the amount to be paid: ";
cin >> N;
int C[n][N+1];
for(int i=0; i<n; i++)
{
C[i][0] = 0;
for(int j=1; j<=N; j++)
{
if(j<arr[i] && i==0)
C[i][j] = 9999;
else if(j>=arr[i] && i==0)
C[i][j] = 1 + C[i][j-arr[i]];
else if(j<arr[i])
C[i][j] = C[i-1][j];
else if(j>=arr[i])
C[i][j] = min( C[i-1][j],1+C[i][j-arr[i]]);
}
}
for(int i=0; i<n; i++)
{
for(int j=0; j<=N; j++)
{
cout << C[i][j] << '\t';
}
cout << "\n";
}
cout << "The minimum no. of coins needed to pay the amount " << N << " is Rs. " << C[n-1][N];
return 0;
}

0 comments on commit 06b9b2d

Please sign in to comment.