Given two objects is there a simple way in Raku to find the nearest common ancestor in their tree of inheritence?
There are already some general answers for this:
How to find nearest common ancestor class of two objects?
Algorithm to find common ancestor of two nodes given
I was wondering if there's an idiomatic solution built-in to Raku already.
Given a binary tree (not a binary search tree) and two values say n1 and n2, write a program to find the least common ancestor. Let T be a rooted tree. The lowest common ancestor between two nodes n1 and n2 is defined as the lowest node in T that has both n1 and n2 as descendants (where we allow a node to be a descendant of itself).
The main idea here is to try a huge jump at first. If doing a huge jump on both pointers leads them to the same node, then we have arrived at a common ancestor. However, we may have jumped too far. There could be some deeper common ancestor. So we can’t do this jump, let’s try something smaller.
2. Definition The Lowest Common Ancestor (LCA) of two nodes and in a rooted tree is the lowest (deepest) node that is an ancestor of both and . Remember that an ancestor of a node in a rooted tree is any node that lies on the path from the root to (including ).
The LCA of n1 and n2 in T is the shared ancestor of n1 and n2 that is located farthest from the root.
class A {}
class B is A {}
class C is B {}
class D is B {}
class E is D {}
say E.^parents.first: * === D.^parents.any
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With