Home / Uncategorized / Execute all the tasks in such a way that if there are no dependencies then the tasks can be started but if there are any dependencies then those tasks should execute once the dependency are completed. for the below tasks Object the output should be in the below way:-Input:-d-done b-done a-done c-done e-done

Execute all the tasks in such a way that if there are no dependencies then the tasks can be started but if there are any dependencies then those tasks should execute once the dependency are completed. for the below tasks Object the output should be in the below way:-Input:-d-done b-done a-done c-done e-done

  • Nodejs
  • JavaScript

const tasks = {
    'd': ['b', 'c'],
    'b': ['a'],
    'a': [],
    'c': [],
    'e': ['d']
};

// Helper function to perform topological sort
function topologicalSort(tasks) {
    const inDegree = {};
    const adjList = {};
    const zeroInDegreeQueue = [];
    const sortedOrder = [];

    // Initialize inDegree and adjList
    for (const [task, dependencies] of Object.entries(tasks)) {
        if (!inDegree[task]) inDegree[task] = 0;
        if (!adjList[task]) adjList[task] = [];

        for (const dependency of dependencies) {
            if (!inDegree[dependency]) inDegree[dependency] = 0;
            if (!adjList[dependency]) adjList[dependency] = [];
            adjList[dependency].push(task);
            inDegree[task]++;
        }
    }

    // Find all tasks with zero in-degree
    for (const task in inDegree) {
        if (inDegree[task] === 0) {
            zeroInDegreeQueue.push(task);
        }
    }

    // Perform the topological sort
    while (zeroInDegreeQueue.length > 0) {
        const currentTask = zeroInDegreeQueue.shift();
        sortedOrder.push(currentTask);

        if (adjList[currentTask]) {
            for (const neighbor of adjList[currentTask]) {
                inDegree[neighbor]--;
                if (inDegree[neighbor] === 0) {
                    zeroInDegreeQueue.push(neighbor);
                }
            }
        }
    }

    // Check for cycles
    if (sortedOrder.length !== Object.keys(tasks).length) {
        throw new Error('There is a cycle in the graph');
    }

    return sortedOrder;
}

// Function to execute a task (returns a Promise)
function executeTask(task) {
    return new Promise((resolve) => {
        console.log(`${task} done`);
        resolve();
    });
}

// Main function to execute tasks in the topologically sorted order
async function executeTasks() {
    try {
        const sortedTasks = topologicalSort(tasks);
        for (const task of sortedTasks) {
            await executeTask(task);
        }
    } catch (error) {
        console.error(error.message);
    }
}

// Run the function to execute the tasks
executeTasks();

const tasks = {
    'd': ['b', 'c'],
    'b': ['a'],
    'a': [],
    'c': [],
    'e': ['d']
};

// Helper function to perform topological sort
function topologicalSort(tasks) {
    const inDegree = {};
    const adjList = {};
    const zeroInDegreeQueue = [];
    const sortedOrder = [];

    // Initialize inDegree and adjList
    for (const [task, dependencies] of Object.entries(tasks)) {
        if (!inDegree[task]) inDegree[task] = 0;
        if (!adjList[task]) adjList[task] = [];

        for (const dependency of dependencies) {
            if (!inDegree[dependency]) inDegree[dependency] = 0;
            if (!adjList[dependency]) adjList[dependency] = [];
            adjList[dependency].push(task);
            inDegree[task]++;
        }
    }

    // Find all tasks with zero in-degree
    for (const task in inDegree) {
        if (inDegree[task] === 0) {
            zeroInDegreeQueue.push(task);
        }
    }

    // Perform the topological sort
    while (zeroInDegreeQueue.length > 0) {
        const currentTask = zeroInDegreeQueue.shift();
        sortedOrder.push(currentTask);

        if (adjList[currentTask]) {
            for (const neighbor of adjList[currentTask]) {
                inDegree[neighbor]--;
                if (inDegree[neighbor] === 0) {
                    zeroInDegreeQueue.push(neighbor);
                }
            }
        }
    }

    // Check for cycles
    if (sortedOrder.length !== Object.keys(tasks).length) {
        throw new Error('There is a cycle in the graph');
    }

    return sortedOrder;
}

// Execute the tasks in the topologically sorted order
function executeTasks() {
    const sortedTasks = topologicalSort(tasks);
    sortedTasks.forEach(task => {
        console.log(`${task} done`);
    });
}

// Run the function to execute the tasks
executeTasks();

About Sushil Kumar

Check Also

Uber NodeJS JavaScript and ReactJS interview questions answers

Deep Copy vs Shallow Copy Shallow Copy A shallow copy creates a new object with …

Leave a Reply

Your email address will not be published. Required fields are marked *