2

I am working on sequential and parallel programming in javascript, I was able to solve sequential programming but didn't have an idea of how to do the same using parallel programming.

For Sequential problem was :

This is an example of sequential processing where it will start at 1 and go till 3 and add 21 to it. Then it will start at 1 and go till 2 and add 10 to it. In the end, start at 1 and go till 4 and add 1 to it.

For Input : 1 3*21#2*10#4*1 output will be :

22
23
24
11
12
2
3
4
5

I solved using below code

function solution(inputData) { 

    var first = inputData.substring(0, 1);
    if(first == 1)
    {
        //sequential
      var strArr = inputData.split(" ");  //3*21#2*10#4*1
      var strHashSplitArr = strArr[1].split("#");  //3*21 #2*10# 4*1
      for(var i=0;i<strHashSplitArr.length;i++)
      {
        var loopInp = strHashSplitArr[i].split("*");
        var maxVal = parseInt(loopInp[0]);
        var addVal = parseInt(loopInp[1]);

        for(var k=1;k<=maxVal;k++)
        {
        console.log(k+addVal);
        }
      }
    }
} 

But now the problem is with parallel programming

Problem:

For example 2, there are 3 processes to start in parallel and numbers are 1, 2 and 3 with delays 100, 20 and 50 consecutively. Here all the processes will start together but a number with less delay will be printed first. Here the number with less delay is 2.So it will print 21,22 in the meantime 50 ms will be achieved and it will print 51 from 3rd number. Now it is mixed with number 1 and prints 101 and so on.

Input : 2 1*100#2*20#3*50

Output should be :

21
22
51
101
52
53

I didn't try using parallels but sorted with milliseconds but couldn't get the expected output.

Here is JSfiddle code for 2nd .. which is giving wrong output (I am not using parallel approach) : https://jsfiddle.net/mahajan344/0u2ka981/

How can I achieve the same output using parallel JavaScript programming?

4

3 Answers 3

2

I think a solution for the problem using setTimeout may be:

function printParallel(val, delay)
{
    setTimeout(function()
    {
        console.log(val);
    }, delay);
}

function solution(inputData) { 
    var first = inputData.substring(0, 1);
    var strArr = inputData.split(" ");
    var strHashSplitArr = strArr[1].split("#");

    for (var i = 0; i < strHashSplitArr.length; i++)
    {
        var loopInp = strHashSplitArr[i].split("*");
        var maxVal = parseInt(loopInp[0]);
        var modifier = parseInt(loopInp[1]);

        if (first == 1)
        {
            for (var j = 1; j <= maxVal; j++)
            {
                console.log(j+modifier);
            }
        }
        else if (first == 2)
        {
            for (var j = 1; j <= maxVal; j++)
            {
                printParallel(j+modifier, modifier);
            }
        }
    }
}

So you will call solution("1 3*21#2*10#4*1"); and solution("2 1*100#2*20#3*50"); to execute the examples but this won't output as expected because the delay of 100 of number 1 is too big to mix with the printing of number 3.

EDIT:

I think now I understand the goal: yo need to set a timeout between every console.log. This will work as expected:

function printParallel(value, maxVal, modifier)
{
    setTimeout(function()
    {
        console.log(value+modifier);
        if (value < maxVal)
        {
            printParallel(++value, maxVal, modifier)
        }
    }, modifier);
}

function solution(inputData) { 
    var first = inputData.substring(0, 1);
    var strArr = inputData.split(" ");
    var strHashSplitArr = strArr[1].split("#");

    for (var i = 0; i < strHashSplitArr.length; i++)
    {
        var loopInp = strHashSplitArr[i].split("*");
        var maxVal = parseInt(loopInp[0]);
        var modifier = parseInt(loopInp[1]);

        if (first == 1)
        {
            for (var j = 1; j <= maxVal; j++)
            {
                console.log(j+modifier);
            }
        }
        else if (first == 2)
        {
            printParallel(1, maxVal, modifier);
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

For parallel it won't work.. output it will give is 21,22,51,52,53,101 where as expected output for parallel is 21 22 51 101 52 53
I edited my answer and I think it's working properly
2

Consider:

async function delay(n) {
    return new Promise(r => setTimeout(r, n));
}

async function* asyncRange(a, b, d) {
    while (a < b) {
        await delay(d);
        yield a++;
    }
}

async function parallel(...ranges_and_delays) {
    let iters = ranges_and_delays.map(t => asyncRange(...t));

    while (iters.length) {
        await Promise.race(iters.map(async it => {
            let v = await it.next();
            if (!v.done) {
                console.log(v.value)
            } else {
                iters = iters.filter(k => k !== it)
            }
        }));
    }
}


parallel([1, 5, 700], [10, 13, 500], [200, 205, 600])

The idea is to put range generators in an array, start a race between them and print whatever comes first. Once a generator is exhausted, remove it from the list.

Note that this isn't real parallel computing (which is not possible in Javascript), just an imitation.

Comments

0

You cannot run your code in parallel in Javascript. It is single threaded language. However, you can use browser's web APIs to do work in parallel. For example, making xhr call.

Note: You cannot even run your code in parallel with SetTimeout() as it will only run the code when the call stack is empty. It does not actually run the code in parallel.

To develop an understanding of this, you must understand event loop.

https://www.educative.io/edpresso/what-is-an-event-loop-in-javascript

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.