Skip to content

Instantly share code, notes, and snippets.

@kklimuk
Last active November 13, 2023 19:09
Show Gist options
  • Save kklimuk/4a362af9f8b0d00be03fe4334fa23e0f to your computer and use it in GitHub Desktop.
Save kklimuk/4a362af9f8b0d00be03fe4334fa23e0f to your computer and use it in GitHub Desktop.
2023.11.12 - Cassidoo's Interview Question of the Week
// Given a list of tasks, where each task has a duration, and a limited amount of available time to work,
// write a function to return the tasks that can be completed within the given time, without re-ordering
// the original list of tasks.
type Task = { name: string; duration: number };
const tasks = [
{ name: "Task 1", duration: 4 },
{ name: "Task 2", duration: 2 },
{ name: "Task 3", duration: 7 },
{ name: "Task 4", duration: 5 },
{ name: "Task 5", duration: 1 },
{ name: "Task 6", duration: 3 },
];
const timeToWork = 6;
console.log(doTasks(tasks, timeToWork));
// > ['Task 2', 'Task 5', 'Task 6']
function doTasks(tasks: Task[], timeToWork: number) : string[] {
const competitors: { duration: number; tasks: Task[] }[] = [];
for (const task of tasks) {
for (const competitor of competitors) {
const newDuration = competitor.duration + task.duration;
if (newDuration <= timeToWork) {
competitor.tasks.push(task);
competitor.duration = newDuration;
}
}
if (task.duration <= timeToWork) {
const competitor = { duration: task.duration, tasks: [task] };
competitors.push(competitor);
}
}
let highScore = 0;
let winner: Task[] = [];
for (const competitor of competitors) {
if (competitor.tasks.length > highScore) {
highScore = competitor.tasks.length;
winner = competitor.tasks;
}
}
return winner.map((task) => task.name);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment