I have an array of arrays of names that could be represented in Ruby like this:
samples = [
%w[a],
%w[a c],
%w[a],
%w[a],
%w[b],
%w[b],
%w[a],
%w[a e],
%w[a e],
%w[a c d],
%w[a c d],
%w[b],
%w[b c e],
%w[b c e],
%w[a c],
%w[a e],
%w[a e]
]
These are the output of a sampling profiler, where each list of names represents the call stack for a particular sample. I want to display these as a top-down tree of named-values where the value at each node is the sum of hits to that particular call path.
For the above sample input, the output tree should be:
root:0
a:4
e:4
c:2
d:2
b:3
c:0
e:2
(I don't want an ASCII output as shown above, but rather a tree structure that represents this.)
What is simple, efficient code that produces this output?
I have my own solution which I will post as an answer, but which seems to me less than ideal.
Edit: I forgot to include the fact that the tree should be sorted in descending value at each level. I've added sample nodes and changed the output to reflect this.