Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to calculate the value-to-weight ratio for each item.
DSA Typescript
items.forEach(item => item.ratio = item.value [1] item.weight); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using multiplication instead of division.
Using addition or subtraction which does not give a 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 Typescript
items.sort((a, b) => b.ratio [1] a.ratio); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition which does not sort correctly.
Using multiplication or division which are not valid for sorting.
✗ Incorrect
Subtracting a.ratio from b.ratio sorts in descending order by ratio.
3fill in blank
hardFix the error in the loop condition to stop when the knapsack is full or all items are processed.
DSA Typescript
while (i < items.length && capacity [1] 0) {
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' which would stop the loop too early.
Using '==' or '!=' which do not correctly check capacity.
✗ Incorrect
The loop continues while capacity is greater than zero and items remain.
4fill in blank
hardFill both blanks to correctly update the total value and reduce the capacity after taking an item fraction.
DSA Typescript
totalValue += fraction * items[i].[1]; capacity -= fraction * items[i].[2];
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using ratio or index instead of value or weight.
Mixing up value and weight in the calculations.
✗ Incorrect
Multiply fraction by value to add to total value, and by weight to reduce capacity.
5fill in blank
hardFill all three blanks to calculate the fraction of the item taken and increment the index.
DSA Typescript
let fraction = capacity [1] items[i].[2]; i [3] 1;
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using multiplication instead of division for fraction.
Using '-=' instead of '+=' to increment index.
✗ Incorrect
Fraction is capacity divided by weight; index increments by 1.