0
0
DSA Cprogramming~10 mins

Fractional Knapsack Problem in DSA C - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare the structure for an item with weight and value.

DSA C
typedef struct {
    int value;
    int [1];
} Item;
Drag options to blanks, or click blank then click option'
Aweight
Bsize
Ccost
Damount
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'size' or 'cost' instead of 'weight'.
2fill in blank
medium

Complete the code to calculate the value per weight ratio for an item.

DSA C
double ratio = (double)items[i].value / items[i].[1];
Drag options to blanks, or click blank then click option'
Acost
Bweight
Csize
Damount
Attempts:
3 left
💡 Hint
Common Mistakes
Dividing by 'cost' or 'size' which are not defined.
3fill in blank
hard

Fix the error in the comparison function used for sorting items by ratio.

DSA C
int cmp(const void *a, const void *b) {
    Item *itemA = (Item *)a;
    Item *itemB = (Item *)b;
    double rA = (double)itemA->value / itemA->weight;
    double rB = (double)itemB->value / itemB->weight;
    if (rA < rB) return [1];
    else if (rA > rB) return -1;
    else return 0;
}
Drag options to blanks, or click blank then click option'
A1
B-1
C2
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Returning -1 instead of 1 causes ascending order.
4fill in blank
hard

Fill both blanks to update the total value and remaining capacity when taking a fraction of an item.

DSA C
if (items[i].weight <= capacity) {
    totalValue += items[i].value;
    capacity -= items[i].weight;
} else {
    double fraction = (double)capacity / items[i].weight;
    totalValue += items[i].value [1] fraction;
    capacity[2]=capacity;
    break;
}
Drag options to blanks, or click blank then click option'
A*
B+
C-
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Adding fraction instead of multiplying, or subtracting capacity incorrectly.
5fill in blank
hard

Fill all three blanks to complete the main loop that processes items for the fractional knapsack.

DSA C
for (int i = 0; i < n; i++) {
    if (items[i].weight <= [1]) {
        totalValue += items[i].value;
        [2] -= items[i].weight;
    } else {
        double fraction = (double)[3] / items[i].weight;
        totalValue += items[i].value * fraction;
        break;
    }
}
Drag options to blanks, or click blank then click option'
Acapacity
BtotalValue
Cweight
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong variables like 'totalValue' or 'weight' in place of capacity.