{"id":136378,"date":"2024-07-12T05:01:05","date_gmt":"2024-07-12T05:01:05","guid":{"rendered":"https:\/\/www.sushilkumar.ind.in\/blog\/?p=136378"},"modified":"2024-07-12T05:20:31","modified_gmt":"2024-07-12T05:20:31","slug":"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","status":"publish","type":"post","link":"https:\/\/www.sushilkumar.ind.in\/blog\/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\/","title":{"rendered":"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"},"content":{"rendered":"\n<div class=\"wp-block-gutena-tabs gutena-tabs-block gutena-tabs-block-e158d0-d9\"><ul class=\"gutena-tabs-tab tab-center\"><li class=\"gutena-tab-title active\" data-tab=\"1\"><div class=\"gutena-tab-title-content icon-top\"><div class=\"gutena-tab-title-text\"><div>Nodejs<\/div><\/div><\/div><\/li><li class=\"gutena-tab-title inactive\" data-tab=\"2\"><div class=\"gutena-tab-title-content icon-top\"><div class=\"gutena-tab-title-text\"><div>JavaScript<\/div><\/div><\/div><\/li><\/ul><div class=\"gutena-tabs-content\">\n<div class=\"wp-block-gutena-tab gutena-tab-block gutena-tab-block-cf8387-eb active\" data-tab=\"1\">\n<p style=\"margin-top:0;margin-bottom:0\"><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const tasks = {\n    'd': &#91;'b', 'c'],\n    'b': &#91;'a'],\n    'a': &#91;],\n    'c': &#91;],\n    'e': &#91;'d']\n};\n\n\/\/ Helper function to perform topological sort\nfunction topologicalSort(tasks) {\n    const inDegree = {};\n    const adjList = {};\n    const zeroInDegreeQueue = &#91;];\n    const sortedOrder = &#91;];\n\n    \/\/ Initialize inDegree and adjList\n    for (const &#91;task, dependencies] of Object.entries(tasks)) {\n        if (!inDegree&#91;task]) inDegree&#91;task] = 0;\n        if (!adjList&#91;task]) adjList&#91;task] = &#91;];\n\n        for (const dependency of dependencies) {\n            if (!inDegree&#91;dependency]) inDegree&#91;dependency] = 0;\n            if (!adjList&#91;dependency]) adjList&#91;dependency] = &#91;];\n            adjList&#91;dependency].push(task);\n            inDegree&#91;task]++;\n        }\n    }\n\n    \/\/ Find all tasks with zero in-degree\n    for (const task in inDegree) {\n        if (inDegree&#91;task] === 0) {\n            zeroInDegreeQueue.push(task);\n        }\n    }\n\n    \/\/ Perform the topological sort\n    while (zeroInDegreeQueue.length > 0) {\n        const currentTask = zeroInDegreeQueue.shift();\n        sortedOrder.push(currentTask);\n\n        if (adjList&#91;currentTask]) {\n            for (const neighbor of adjList&#91;currentTask]) {\n                inDegree&#91;neighbor]--;\n                if (inDegree&#91;neighbor] === 0) {\n                    zeroInDegreeQueue.push(neighbor);\n                }\n            }\n        }\n    }\n\n    \/\/ Check for cycles\n    if (sortedOrder.length !== Object.keys(tasks).length) {\n        throw new Error('There is a cycle in the graph');\n    }\n\n    return sortedOrder;\n}\n\n\/\/ Function to execute a task (returns a Promise)\nfunction executeTask(task) {\n    return new Promise((resolve) => {\n        console.log(`${task} done`);\n        resolve();\n    });\n}\n\n\/\/ Main function to execute tasks in the topologically sorted order\nasync function executeTasks() {\n    try {\n        const sortedTasks = topologicalSort(tasks);\n        for (const task of sortedTasks) {\n            await executeTask(task);\n        }\n    } catch (error) {\n        console.error(error.message);\n    }\n}\n\n\/\/ Run the function to execute the tasks\nexecuteTasks();\n<\/code><\/pre>\n<\/div>\n\n\n\n<div class=\"wp-block-gutena-tab gutena-tab-block gutena-tab-block-56b57a-40 inactive\" data-tab=\"2\">\n<p style=\"margin-top:0;margin-bottom:0\"><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const tasks = {\n    'd': &#91;'b', 'c'],\n    'b': &#91;'a'],\n    'a': &#91;],\n    'c': &#91;],\n    'e': &#91;'d']\n};\n\n\/\/ Helper function to perform topological sort\nfunction topologicalSort(tasks) {\n    const inDegree = {};\n    const adjList = {};\n    const zeroInDegreeQueue = &#91;];\n    const sortedOrder = &#91;];\n\n    \/\/ Initialize inDegree and adjList\n    for (const &#91;task, dependencies] of Object.entries(tasks)) {\n        if (!inDegree&#91;task]) inDegree&#91;task] = 0;\n        if (!adjList&#91;task]) adjList&#91;task] = &#91;];\n\n        for (const dependency of dependencies) {\n            if (!inDegree&#91;dependency]) inDegree&#91;dependency] = 0;\n            if (!adjList&#91;dependency]) adjList&#91;dependency] = &#91;];\n            adjList&#91;dependency].push(task);\n            inDegree&#91;task]++;\n        }\n    }\n\n    \/\/ Find all tasks with zero in-degree\n    for (const task in inDegree) {\n        if (inDegree&#91;task] === 0) {\n            zeroInDegreeQueue.push(task);\n        }\n    }\n\n    \/\/ Perform the topological sort\n    while (zeroInDegreeQueue.length > 0) {\n        const currentTask = zeroInDegreeQueue.shift();\n        sortedOrder.push(currentTask);\n\n        if (adjList&#91;currentTask]) {\n            for (const neighbor of adjList&#91;currentTask]) {\n                inDegree&#91;neighbor]--;\n                if (inDegree&#91;neighbor] === 0) {\n                    zeroInDegreeQueue.push(neighbor);\n                }\n            }\n        }\n    }\n\n    \/\/ Check for cycles\n    if (sortedOrder.length !== Object.keys(tasks).length) {\n        throw new Error('There is a cycle in the graph');\n    }\n\n    return sortedOrder;\n}\n\n\/\/ Execute the tasks in the topologically sorted order\nfunction executeTasks() {\n    const sortedTasks = topologicalSort(tasks);\n    sortedTasks.forEach(task => {\n        console.log(`${task} done`);\n    });\n}\n\n\/\/ Run the function to execute the tasks\nexecuteTasks();\n<\/code><\/pre>\n<\/div>\n<\/div><\/div>\n","protected":false},"excerpt":{"rendered":"<p>NodejsJavaScript const tasks = { &#8216;d&#8217;: &#91;&#8217;b&#8217;, &#8216;c&#8217;], &#8216;b&#8217;: &#91;&#8217;a&#8217;], &#8216;a&#8217;: &#91;], &#8216;c&#8217;: &#91;], &#8216;e&#8217;: &#91;&#8217;d&#8217;] }; \/\/ Helper function to perform topological sort function topologicalSort(tasks) { const inDegree = {}; const adjList = {}; const zeroInDegreeQueue = &#91;]; const sortedOrder = &#91;]; \/\/ Initialize inDegree and adjList for (const &#91;task, dependencies] of Object.entries(tasks)) { &hellip;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","enabled":false},"version":2}},"categories":[1],"tags":[],"class_list":["post-136378","post","type-post","status-publish","format-standard","","category-uncategorized"],"jetpack_publicize_connections":[],"acf":[],"aioseo_notices":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p99pkJ-ztE","_links":{"self":[{"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/posts\/136378"}],"collection":[{"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/comments?post=136378"}],"version-history":[{"count":3,"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/posts\/136378\/revisions"}],"predecessor-version":[{"id":136390,"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/posts\/136378\/revisions\/136390"}],"wp:attachment":[{"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/media?parent=136378"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/categories?post=136378"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.sushilkumar.ind.in\/blog\/wp-json\/wp\/v2\/tags?post=136378"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}