1

I need to order a graph appropriately, considering the levels.

Assuming I have this data:

const people = [
    {
        'name': 'john',
        'level': 0,
        'connections': ['monica', 'jeffrey']
    },
    {
        'name': 'monica',
        'level': 1,
        'connections': ['william']
    },
    {
        'name': 'jeffrey',
        'level': 1,
        'connections': ['george']
    },
    {
        'name': 'george',
        'level': 1,
        'connections': []
    },
    {
        'name': 'william',
        'level': 2,
        'connections': ['rachel']
    },
    {
        'name': 'rachel',
        'level': 3,
        'connections': []
    }
]

How can I go about outputting the correct order in which they should be formed?

Example of correct order:

/*
[
John
- Monica
-- William
--- Rachel
- Jeffrey
-- George
]
*/

// (No need to worry about -)

I tried:

let orderCounter = 1;

people.forEach(person => {
  person['order'] = person['order'] || ++orderCounter;
  if (person.connections > 0)
    person.connections.forEach(connection => {
      const foundPerson = people.find(x => x === connection);
      foundPerson['order'] = foundPerson['order'] || ++orderCounter;
  });
});

I don't really enjoy having so many loops inside one another.

The question is, how can I make this more effective rather than being convoluted?

  • This is a topological sort. The wikipaedia article has several suggestions https://en.wikipedia.org/wiki/Topological_sorting – ravenspoint May 14 '21 at 23:46
  • You are correct @ravenspoint. What I'm looking for is Depth First Search. I'm having some difficulties with multiple parents linking to the same child though. – johntomkmeans May 15 '21 at 18:24
  • The sample problem you posted has no children with multiple parents. In any case, I would not expect the Dijsktra algorithm to have any problem with multiple parents - it would simply give you the minimum depth from root to every node. – ravenspoint May 16 '21 at 14:01

1 Answers1

0

The Dijsktra algorithm is widely available in well tested libraries and provides a straightforward way to solve problems such as this ( and many others too )

Converting your sample data into a space delimited text file with all links costed at 1, running the boost graph implementation of Dijsktra gives output:

C:\Users\James\code\PathFinder\bin>gui
l john monica 1
l john jeffrey 1
l monica william 1
l jeffrey george 1
l william rachel 1
s john
e all


Hop count from root to every node:
john to monica 1
john to jeffrey 1
john to william 2
john to george 2
john to rachel 3

Boost graph implementation of Dijsktra

PathFinder is a C++ wrapper for the Boost graph implementation of Dijsktra.

ravenspoint
  • 19,093
  • 6
  • 57
  • 103