Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to calculate the value-to-weight ratio for each item.
DSA Go
ratio := float64(items[i].value) / float64(items[i].[1])Attempts:
3 left
💡 Hint
Common Mistakes
Using value instead of weight in the denominator.
Using capacity which is unrelated here.
✗ Incorrect
The ratio is value divided by weight to find value per unit weight.
2fill in blank
mediumComplete the code to sort items by their value-to-weight ratio in descending order.
DSA Go
sort.Slice(items, func(i, j int) bool { return items[i].[1] > items[j].[1] })Attempts:
3 left
💡 Hint
Common Mistakes
Sorting by value or weight alone instead of ratio.
Sorting in ascending order instead of descending.
✗ Incorrect
We sort by the ratio to pick items with highest value per weight first.
3fill in blank
hardFix the error in the loop condition to process items until capacity is full or items end.
DSA Go
for i < len(items) && [1] > 0 {
Attempts:
3 left
💡 Hint
Common Mistakes
Using weight or value in the loop condition instead of capacity.
Using ratio which is unrelated here.
✗ Incorrect
The loop continues while there is remaining capacity to fill.
4fill in blank
hardFill both blanks to correctly update total value and remaining capacity after taking an item fraction.
DSA Go
totalValue += fraction * float64(items[i].[1]) capacity -= fraction * items[i].[2]
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up value and weight in calculations.
Using ratio or index instead of value or weight.
✗ Incorrect
Add fraction times value to total value and reduce capacity by fraction times weight.
5fill in blank
hardFill all three blanks to calculate the fraction of the item taken and update total value and capacity.
DSA Go
fraction := float64([1]) / float64(items[i].[2]) totalValue += fraction * float64(items[i].[3]) capacity = 0
Attempts:
3 left
💡 Hint
Common Mistakes
Using value instead of weight for fraction denominator.
Not setting capacity to zero after taking fraction.
✗ Incorrect
Fraction is remaining capacity divided by item weight; total value adds fraction times value; capacity becomes zero after taking fraction.
