Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'size' or 'cost' instead of 'weight'.
✗ Incorrect
The structure must have a field named 'weight' to store the item's weight.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Dividing by 'cost' or 'size' which are not defined.
✗ Incorrect
The ratio is value divided by weight, so 'weight' is the correct field.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning -1 instead of 1 causes ascending order.
✗ Incorrect
For sorting in descending order, return 1 when rA < rB so itemB comes first.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Adding fraction instead of multiplying, or subtracting capacity incorrectly.
✗ Incorrect
Multiply value by fraction to add partial value, then reduce capacity to zero.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong variables like 'totalValue' or 'weight' in place of capacity.
✗ Incorrect
Use 'capacity' to check and update remaining space and calculate fraction.