Sort / reorder objects based on allowed objects

I need to develop an algorithm that will take a set of unordered objects and arrange them reasonably based on the objects that they can go to.

My initial project / thought was to use Core Data to store an object (for example, "Objects") with a to-many relation ("canGoTo") back on itself with a set of objects that can follow the selected objects * object.

Consider the following example, where each object has a set of objects into which it can go (the actual set of objects is much larger).

Object A - can go to -> Objects B,C,D Object B - can go to -> Objects E,F,G,Y,H Object C - can go to -> Objects P,S,Z Object D - can go to -> Objects H,J,X ... Object G - can go to -> Objects R,Y,Z Object H - can go to -> Objects G,Z ... Object Y - can go to -> Objects Z Object Z - can go to -> Objects NULL (no objects follow this object) 

If the program is given a set of objects (R, B, H, G, A, Z), the program must find a way to reassign the objects to find an acceptable structure. Thus, the correct result for this set would be A-> B-> H-> G-> Y-> Z

What is the best or most effective strategy to deal with this problem? Should I go in cycles in repeated orders and leave when I successfully touch all objects in an aisle? Using a genetic algorithm to generate inference and analysis of generations (i.e. http://ijoshsmith.com/2012/04/08/simple-genetic-algorithm-in-objective-c/ )? Or am I using Insertion Sort to analyze all the objects and re-order the object to where it can fit in the sequence? Keep in mind that a real list of objects would be more like 30+ objects, rather than 6, and in an ideal world, the program would choose the best way to organize the list (perhaps based on the priority of "canGoTo").

Any recommendations / best practices are welcome. Sorry for the lack of an example code, this is in the phase of thought at the moment.

+4
source share
1 answer

You can model your problem as a Directed Acyclic Graph and then Topological Sort . This will give the exact result you are looking for.

+1
source

Source: https://habr.com/ru/post/1444361/


All Articles