0
0
DSA Typescriptprogramming~10 mins

Fractional Knapsack Problem in DSA Typescript - Interactive Practice

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

Complete 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'
A*
B+
C/
D-
Attempts:
3 left
💡 Hint
Common Mistakes
Using multiplication instead of division.
Using addition or subtraction which does not give a ratio.
2fill in blank
medium

Complete 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'
A-
B+
C*
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition which does not sort correctly.
Using multiplication or division which are not valid for sorting.
3fill in blank
hard

Fix 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'
A!=
B>
C<
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' which would stop the loop too early.
Using '==' or '!=' which do not correctly check capacity.
4fill in blank
hard

Fill 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'
Avalue
Bweight
Cratio
Dindex
Attempts:
3 left
💡 Hint
Common Mistakes
Using ratio or index instead of value or weight.
Mixing up value and weight in the calculations.
5fill in blank
hard

Fill 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'
A/
Bweight
C+=
D-=
Attempts:
3 left
💡 Hint
Common Mistakes
Using multiplication instead of division for fraction.
Using '-=' instead of '+=' to increment index.