Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to calculate the value-to-weight ratio for each item.
DSA Javascript
const ratio = items.map(item => item.value [1] item.weight);Attempts:
3 left
💡 Hint
Common Mistakes
Using multiplication instead of division.
Using addition or subtraction which does not give the ratio.
✗ Incorrect
The value-to-weight ratio is calculated by dividing the value by the weight.
2fill in blank
mediumComplete the code to sort items by their value-to-weight ratio in descending order.
DSA Javascript
items.sort((a, b) => b.[1] - a.[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 property to get items with highest value per weight first.
3fill in blank
hardFix the error in the loop condition to correctly process all items.
DSA Javascript
for (let i = 0; i [1] items.length && capacity > 0; i++) {
Attempts:
3 left
💡 Hint
Common Mistakes
Using greater than or equal which causes no iterations or errors.
Using greater than which never runs the loop.
✗ Incorrect
The loop should run while i is less than items.length to avoid going out of bounds.
4fill in blank
hardFill both blanks to correctly calculate the fraction of the item to take and update capacity.
DSA Javascript
const fraction = Math.min(1, capacity [1] item.weight); capacity [2]= fraction * item.weight;
Attempts:
3 left
💡 Hint
Common Mistakes
Using multiplication instead of division for fraction.
Adding to capacity instead of subtracting.
✗ Incorrect
Fraction is capacity divided by item weight, and capacity is reduced by fraction times item weight.
5fill in blank
hardFill all three blanks to update total value and print the final result.
DSA Javascript
totalValue [1]= fraction * item.[2]; console.log('Total value: ' + totalValue.toFixed([3]));
Attempts:
3 left
💡 Hint
Common Mistakes
Using -= instead of += causing wrong total.
Using weight instead of value for calculation.
Not formatting output or using wrong decimal places.
✗ Incorrect
Add fraction times item value to totalValue and print with 2 decimal places.
