0
0
DSA Typescriptprogramming~30 mins

Why Greedy Works and When It Fails in DSA Typescript - See It Work

Choose your learning style9 modes available
Why Greedy Works and When It Fails
📖 Scenario: Imagine you are organizing a small event and need to select tasks to complete within a limited time. Each task has a duration and a value representing its importance. You want to pick tasks to maximize total importance without exceeding the available time.This project will help you understand how a greedy approach can work well in some cases and fail in others.
🎯 Goal: You will build a simple program that selects tasks using a greedy method based on task duration. Then, you will see when this approach fails and why.
📋 What You'll Learn
Create an array of tasks with exact durations and values
Set a total available time limit
Implement a greedy selection of tasks by shortest duration first
Print the selected tasks and total value
💡 Why This Matters
🌍 Real World
Task scheduling and resource allocation often use greedy methods for quick decisions.
💼 Career
Understanding when greedy algorithms work or fail helps in software engineering, operations research, and optimization roles.
Progress0 / 4 steps
1
Create the tasks array
Create an array called tasks with these exact objects: {name: 'Task1', duration: 1, value: 10}, {name: 'Task2', duration: 3, value: 20}, {name: 'Task3', duration: 2, value: 15}, {name: 'Task4', duration: 4, value: 40}.
DSA Typescript
Hint

Use an array of objects with keys name, duration, and value.

2
Set the total available time
Create a variable called totalTime and set it to 5 to represent the total available time for tasks.
DSA Typescript
Hint

Use const totalTime = 5; to set the time limit.

3
Select tasks greedily by shortest duration
Create a variable called selectedTasks as an empty array. Use tasks.sort((a, b) => a.duration - b.duration) to sort tasks by duration ascending. Then use a for loop with variable task over tasks. Keep track of usedTime starting at 0. For each task, if usedTime + task.duration <= totalTime, add task to selectedTasks and add task.duration to usedTime.
DSA Typescript
Hint

Sort tasks by duration, then pick tasks while total time allows.

4
Print selected tasks and total value
Print the names of tasks in selectedTasks separated by commas using console.log. Then print the total value of selected tasks by summing task.value for each task in selectedTasks.
DSA Typescript
Hint

Use map and join to print names, and reduce to sum values.