I have a list of pairs with class inheritance information like this
[
[Person, null],
开发者_如何学编程 [Person, SpecialPerson], // Person extends SpecialPerson
[SpecialPerson, VerySpecialPerson], // SpecialPerson extends VerySpecialPerson
]
Is there any particular algorithm to flatten this information?
Like this:
Person -> SpecialPerson -> VerySpecialPerson
In the end, it boils down to a DAG (directed acyclic graph). Therefore you would do a breadth-first search or depth-first search. You only need the simplified case for trees.
Example (BFS, pseudo-code, untested):
List<Array<Typespec>> flatten(Array<Pair<Typespec,Typespec>> input) {
List<Array<Typespec>> result;
Queue<Array<Typespec>*> q;
var elem=&result.append([null]);
q.append(elem);
while (!q.empty()) {
for (i in input) {
if (i.first==q.front().back()) {
var elem=&result.append(q.front().clone().append(i.second));
q.append(elem);
}
}
q.pop_front();
}
return result;
}
This assumes that you meant [null,Person]
, instead of the other way round. Note that it produces a null
at the start of every result, differing from your example.
精彩评论