JavaScript group array - find the sets of numbers that can be traveled to using the edges defined

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Consider the following input and output arrays −

const input = ["0:3", "1:3", "4:5", "5:6", "6:8"]; const output = [
   [0, 1, 3],
   [4, 5, 6, 8]
];

Considering each number as a node in a graph, and each pairing x:y as an edge between nodes x and y, we are required to find the sets of numbers that can be traveled to using the edges defined.

That is, in graph theory terms, find the distinct connected components within such a graph. For instance, in the above arrays, there is no way to travel from 4 to 0 so they are in different groups, but there is a way to travel from 1 to 0 (by way of 3) so they are in the same group." To reiterate the desired output is a grouping of transversable nodes, based on a potentially random input set.

We are required to write a JavaScript function that constructs the desired output from the given input.

Example

const input = ["0:3", "1:3", "4:5", "5:6", "6:8"];
const groupRange = (arr = []) => {
   const res = [[]];
   let count = 0;
   const a = [0];
   let array = arr.map(el => el.split(':').sort((a, b) => a - b)). sort((a, b) => a[0] - b[0]); array.forEach(el => {
      if (el[0] > a[a.length - 1]) {
         res.push(el);
          a.push(el[1]);
         count++;
      } else {
         res[count] = res[count].concat(el);
         a[a.length - 1] = el[1];
      };
   });
   return res.map(el => [...new Set(el)].sort((a, b) => a - b));
}
console.log(groupRange(input));

Output

And the output in the console will be −

[ [ '0', '1', '3' ], [ '4', '5', '6', '8' ] ]
raja
Published on 21-Nov-2020 05:49:29
Advertisements