in reply to Sort mechanics problems with objects and potentially contradicting comparisons (would cause infinite loop)
I would say that the task of detecting circular references in a data structure does not involve sorting at all. Simply walk the data structure/hierarchy/whatever while keeping track of the path you followed to get there.
Here's some untested code to show what I mean:
sub is_circular { my $obj = shift; # Object to be traversed my $path = shift || []; # Check of $obj is in the $path foreach my $ancestor (@{$path}) { return 1 if $ancestor eq $obj; } # Check the children recursively, depth first # (My imaginary $obj conveniently has # a method for getting an array of its children) foreach my $child ($obj->children) { return 1 if is_circular($child, [ @{$path}, $obj ] ); } return 0; }
This can be done recursively or in a linear fashion if this suits you better. Modules already exist but writing your own code would probably be faster than trying to fit an existing module with your particular data.
Time flies when you don't know what you're doing
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Sort mechanics problems with objects and potentially contradicting comparisons (would cause infinite loop)
by anonymized user 468275 (Curate) on Jun 02, 2016 at 11:06 UTC | |
by Anonymous Monk on Jun 02, 2016 at 16:45 UTC | |
by anonymized user 468275 (Curate) on Jun 15, 2016 at 13:14 UTC |