On reflection, I thought this might benefit from an alternative recursive implementation that uses a different partitioning strategy that avoids overconstraint, and does not rely on function calls to implement the recursive policy.
// Note: Assumes that there is a valid topological ordering.constorderTasks=(tasks)=>{constresolvedTasks=newSet();constorderedTasks=[];constunorderedTasks=[...tasks];constprocessFirstUnorderedTask=(task)=>{for(constdependencyoftask.depends){if(!resolvedTasks.has(dependency)){// Schedule the task for backtracking.unorderedTasks.push(task);return;}}// Reduce the size of the problem.resolvedTasks.add(task.task);orderedTasks.push(task);}while(unorderedTasks.length>0){// Take the first unordered task.consttask=unorderedTasks.shift();// Reduce the size of the problem, or schedule it for backtracking.processFirstUnorderedTask(task);}returnorderedTasks;}constunorderedTasks=[{task:"buy groceries",depends:["go to the store"]},{task:"make a sandwich",depends:["buy groceries"]},{task:"go to the store",depends:[]}];constorderedTasks=orderTasks(unorderedTasks);console.log(JSON.stringify(orderedTasks,null,2));
Thanks so much for taking a stab at it. As someone who's still learning data structures and CS fundamentals, I really admire your backtracking technique here. It has truly expanded my knowledge of recursion.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
On reflection, I thought this might benefit from an alternative recursive implementation that uses a different partitioning strategy that avoids overconstraint, and does not rely on function calls to implement the recursive policy.
Thanks so much for taking a stab at it. As someone who's still learning data structures and CS fundamentals, I really admire your backtracking technique here. It has truly expanded my knowledge of recursion.