You are on page 1of 2

Academic Year: 2023-24

60003220001
COURSE CODE: DJ19ITL403 DATE: 19/02/24
COURSE NAME: Design and Analysis of Algorithm Laboratory CLASS: S. Y. B.Tech
Name :Shubham Singh Roll No: I156

Experiment 2
Greedy Algorithm
Aim: You are an adventurer exploring a desert oasis in search of valuable resources. Along your
journey, you come across various types of fruits scattered around the oasis. Each fruit has a
specific weight and nutritional value. Your goal is to determine the maximum total nutritional
value you can carry in your backpack without exceeding its weight capacity. You have the
flexibility to take fractional parts of fruits, optimizing your backpack's load for maximum
nutritional value. Choose wisely to ensure you have enough energy to continue your exploration
through the desert.

Lab Assignment to Complete:


The capacity of the knapsack W = 60 and the list of provided items are shown in the
following table –
Item A B C D
Profit 280 100 120 120

Weight 40 10 20 24

CODE:
#include <stdio.h>

int n = 4;
int c[10] = {40,10,20,24};
int v[10] = {280,100,120,120};
int W = 60;

void simple_fill() {
int cur_w;
float tot_v;
int i, maxi;
int used[10];

for (i = 0; i < n; ++i)


used[i] = 0;

cur_w = W;
while (cur_w > 0) {
maxi = -1;
for (i = 0; i < n; ++i)
Academic Year: 2023-24

60003220001
if ((used[i] == 0) &&
((maxi == -1) || ((float)v[i]/c[i] > (float)v[maxi]/c[maxi])))
maxi = i;

used[maxi] = 1;
cur_w -= c[maxi];
tot_v += v[maxi];
if (cur_w >= 0)
printf("Added object %d (%d$, %dKg) completely in the bag. Space left: %d.\n", maxi + 1,
v[maxi], c[maxi], cur_w);
else {
printf("Added %d%% (%d$, %dKg) of object %d in the bag.\n", (int)((1 + (float)cur_w/c[maxi])
* 100), v[maxi], c[maxi], maxi + 1);
tot_v -= v[maxi];
tot_v += (1 + (float)cur_w/c[maxi]) * v[maxi];
}
}

printf("Filled the bag with profit %.2f$.\n", tot_v);


}

int main(int argc, char *argv[]) {


simple_fill();

return 0;
}

OUTPUT:

You might also like