r/dailyprogrammer • u/Cosmologicon 2 3 • Jan 25 '19
[2019-01-25] Challenge #373 [Hard] Embeddable trees
Today's challenge requires an understanding of trees in the sense of graph theory. If you're not familiar with the concept, read up on Wikipedia or some other resource before diving in.
Today we're dealing with unlabeled, rooted trees. We'll need to be able to represent fairly large trees. I'll use a representation I just made up (but you can use anything you want that's understandable):
- A leaf node is represented by the string
"()". - A non-leaf node is represented by
"(", followed by the representations of its children concatenated together, followed by")". - A tree's representation is the same as that of its root node.
For instance, if a node has two children, one with representation (), and one with representation (()()), then that node's representation is ( + () + (()()) + ) = (()(()())). This image illustrates the following example trees:
((()))(()())((())(()))((((()()))(()))((((()()))))((())(())(())))
In this image, I've colored some of the nodes so you can more easily see which parentheses correspond to which nodes, but the colors are not significant: the nodes are actually unlabeled.
Warmup 1: equal trees
The ordering of child nodes is unimportant. Two trees are equal if you can rearrange the children of each one to produce the same representation. This image shows the following pairs of equal trees:
((())()) = (()(()))((()((())()))(())) = ((())(()(()(()))))
Given representations of two trees, determine whether the two trees are equal.
equal("((()((())()))(()))", "((())(()(()(()))))") => true
equal("((()))", "(()())") => false
equal("(((()())())()())", "(((()())()())())") => falseIt's easy to make a mistake, so I highly recommend checking yourself before submitting your answer! Here's a list of 200 randomly-generated pairs of trees, one pair on each line, separated by a space. For how many pairs is the first tree equal to the second?
Warmup 2: embeddable trees
One tree is homeomorphically embeddable into another - which we write as <= - if it's possible to label the trees' nodes such that:
- Every label is unique within each tree.
- Every label in the first tree appears in the second tree.
- If two nodes appear in the first tree with labels X and Y, and their lowest common ancestor is labeled Z in the first tree, then nodes X and Y in the second tree must also have Z as their lowest common ancestor.
This image shows a few examples:
(()) <= (()())(()()) <= (((())()))(()()())is not embeddable in((()())()). The image shows one incorrect attempt to label them: in the first graph, B and C have a lowest common ancestor of A, but in the second graph, B and C's lowest common ancestor is the unlabeled node.(()(()())) <= (((((())()))())((()()))). There are several different valid labelings in this case. The image shows one.
Given representations of two trees, determine whether the first is embeddable in the second.
embeddable("(())", "(()())") => true
embeddable("(()()())", "((()())())") => falseIt's easy to make a mistake, so I highly recommend checking yourself before submitting your answer! Here's a list of 200 randomly-generated pairs of trees, one pair on each line, separated by a space. For how many pairs is the first embeddable into the second?
Challenge: embeddable tree list
Generate a list of trees as long as possible such that:
- The first tree has no more than 4 nodes, the second has no more than 5, the third has no more than 6, etc.
- No tree in the list is embeddable into a tree that appears later in the list. That is, there is no pair of indices i and j such that i < j and the i'th tree <= the j'th tree.
3
u/porthos3 Jan 25 '19 edited Jan 25 '19
Would it be correct to rephrase your definition of homeomorphically embeddable to say:
embeddable(a, b)is true if b can be made identical to a purely by pruning the graph b?If I adapt your notation to include a name as the first item in the parentheses (e.g.
(A(B)(C))instead of(()())):(A(B)) <= (X(Y)(Z))is true because you can prune either Y or Z from the second graph to turn it into the first graph.(A(B)(C)) <= (D(E(F(G))(H)))is true because you can prune D and G.(A(B)(C)(D)) <= (E(F(G)(H))(I))is NOT true, because the first graph does not appear anywhere within the second graph, so no amount of pruning will result in it.(A(B)(C(D)(E))) <= (F(G(H(I(J(K))(L)))(M))(N(O(P)(Q))))is true, because you can prune I (and all of its children) and P and Q?Note: By "pruning", I mean severing one edge to create two subgraphs and discarding either graph. You can cut off a subtree from the head of the tree and keep the subtree.
5
u/porthos3 Jan 25 '19 edited Jan 26 '19
Clojure
Create a function called read-tree that converts a string representation of a tree to nested lists:
Warm Up 1
This function takes any number of trees and returns false if any two of them are not equal.
This determines there are 121 equal trees in this first set.
Warm Up 2
There are three cases in which tree-embeddable? will return true:
aandbhave no childrenacan be paired with a distinct child ofbwith which it is embeddableThe entirety of
ais embeddable within one child ofb(defn pairable? [pred aset bset & [used-indices]] (or (empty? aset) (some (fn [i] (and (not ((or used-indices #{}) i)) (pred (first aset) (nth bset i)) (pairable? pred (rest aset) bset (conj (or used-indices #{}) i)))) (range (count bset)))))
(defn tree-embeddable? [a b] (or (and (empty? a) (empty? b)) (and (<= (count a) (count b)) (pairable? tree-embeddable? a b)) (some #(tree-embeddable? a %) b)))
3
u/NSzx Jan 27 '19 edited Jan 27 '19
Javascript ES6 no library warmup 1 and 2
Results:
Code:
Edit: Corrected a wrong condition in the
embeddablemethod2
u/Lopsidation Jan 25 '19 edited Jan 26 '19
Python, embeddable task in polynomial time
EDIT: Explanation totally rewritten for clarity.
How can we quickly decide whether a tree T embeds into another tree S? First, define a tree's "children" to be the subtrees rooted at the immediate children of the tree's root. Then T embeds into S if either:
Note that if T has no children (i.e. T is just the root node), then the second condition is always vacuously true.
Using the above rules, we can solve the problem with a dynamic programming approach, computing for each pair (t,s) of nodes in T and S whether the subtree rooted at t embeds into the subtree rooted at s.
However, there's a catch. That second rule is a little tricky. It's more complicated than just "every child of T embeds into some child of S." Here's an example. Say S has 3 children, and name them A,B,C. Say T has 3 children, one of which can embed into either A or B, while the other two can only embed into C. Then T can't embed into S, because such an embedding would need to use the child C twice.
Implementing this rule is actually a previous dailyprogrammer challenge! The "resources" are T's children (A, B, and C in the above example), and the "resource cards" are S's children. I wrote that challenge, so I have an advantage here... but I just call the networkx library anyway. It has a "maximum_matching" function that does exactly what I want.
I count 138 pairs in the test file where the first tree embeds into the second. My code takes around 6 minutes to run, about 2/3 of which is inside the maximum_matching function.
2
u/Godspiral 3 3 Jan 26 '19
in J,
just first part. Transform into a sortable entity, and J's nested boxes is a solution.
(<(<(<'')),(<(<''),(<(<''),(<(<'')))))
lazy version hardcoded to 3 levels, sort at each level
2
u/ephemient Jan 30 '19 edited Apr 24 '24
This space intentionally left blank.
1
u/WhiteKnightC Jan 27 '19
Python
Only warmup 1, I'd try to do warmup 2. ATM my brain doesn't want to learn the warmup 2 concept.
1
u/kurodoll Jan 27 '19
Python
Just the first warmup. I get 121 for the count.
I just count sub-tree lengths or something.
1
u/tomekanco Jan 27 '19 edited Jan 27 '19
When stating that the trees are rooted, i assume this implies that the root is fixed; meaning the graph is directed (similar to how calculations are evaluated).
In this case i find 110 equals for Warmup 1.
I basically sort the graph according to max depth and number of nodes for each subgraph.
Python3
1
u/[deleted] Feb 01 '19
Haskell, warmup 1:
1
u/ni3t Feb 01 '19 edited Feb 01 '19
Ruby 2.6
Warm-up 1 - 121 pairs
ruby 373.rb 0.24s user 0.08s system 80% cpu 0.397 totalUsing gsub to turn
(())into[[]]Then eval'ing to turn into an actual array
Then recursively sorting and comparing sorted arrays
...data
1
u/mantheflan Jun 26 '19
Python
Warm-up 1 only
Hi everyone, I'm a bit late to the party but I have an issue with my code that I can't quite pinpoint. I am new to the sub and not a very experienced programmer so if there's anything I should or shouldn't be doing please let me know. I'm also not used to markdown but I'll do my best to format this comment as it should be.
Basically I have trouble figuring out how to explain why two trees are equal, but it is easy to see when they are not. So I wrote a recursive function that looks at individual branches and tries to match them, using another function that takes a tree and outputs a lists of all its "first-generation children", if that makes sense.
It works for a number of simple examples but when I try the randomly generated ones, I get 0 equal pairs.
Here it is: