3
$\begingroup$

I have a question about drawing tree graph. I use my iterative code to build a tree graph. Here it is.

ClearAll["Global`*"];
(*der={1,3,4,2};*)
der = Input["Add a lot of points in each level, enclosed in curly braces.
(contoh = {1,3,4,2}) : "]
awal = 1;
agab = {};
tekan = 1;
For[k = 1, k <= Count[der, _Integer] - 1, k++,
  If[k == 1, mbiyen = 0, tekan = der[[k - 1]]];
  For[l = 1, l <= tekan, l++,
   For[j = 1, j <= der[[k]], j++,
     a[j + mbiyen] = 
      Table[j + mbiyen \[UndirectedEdge] i, {i, awal + 1, 
        awal + der[[k + 1]]}];
     agab = agab \[Union] a[j + mbiyen];
     awal = awal + der[[k + 1]];
     If[j == der[[k]], mbiyen = j + mbiyen];
     ];
   ];
  ];
agab
Graph[agab, VertexLabels -> "Name", ImagePadding -> 10]

Now, I use{1,3,4,2} into input form. Then the graph looks like this 1,3,4,2 tree graph

But I have a problem when the levels are more than 4. It still left the vertex. Can anyone fix this code? Or maybe change into recursive mode? Thanks in advance.

$\endgroup$
2
  • 1
    $\begingroup$ Can you elaborate more on what kind of graph you try to create? I thought I understood it but the output of {2,3,4} got me thinking. $\endgroup$
    – halirutan
    Commented Apr 9, 2014 at 18:38
  • $\begingroup$ Thanks Sjoerd,<br>That is tree graph. On my example above, {1,3,4,2} : The first level is just 1 vertex, the 2nd level are 3 vertex, the 3rd level are 4 vertex. So I don't use {2,3,4}, but the first must be 1. Then, my code can walk no more than 4 levels. $\endgroup$
    – recobayu
    Commented Apr 9, 2014 at 18:51

2 Answers 2

3
$\begingroup$

Let me give a short and readable implementation which uses the function nextLevel as its core. It's only three small lines which need to be understood:

nextLevel[{v_, _}, n_] := Block[{c = Last[v] + 1, ids, i = 1},
   ids = Range[c, c + Length[v]*n - 1];
   {ids, Table[UndirectedEdge[k, ids[[i++]]], {k, v}, {n}]}
];

The function nextLevel takes a list of graph vertices from one level v and a number of children which the vertices will have. In your example, this would give in the second level the list {2,3,4} as vertices and 4 because they split each into 4 new children. First, the function calculates c which is the id of the next node (after vertex 4 comes 5). Then it creates a list of all children in the next level. This would be the list {5,6,...,16}. The Table call creates the edges by connecting the current vertices with the correct child vertices. As return value, we give back ids which is the list of child vertices required for the iteration in the next round and all edges from this level of the tree to the next.

That's it. The only thing that's left is to use FoldList to iterate over your list of tree depths:

makeTree[depths : {_Integer ..}] := 
 Flatten[FoldList[nextLevel, {{1}, {}}, depths][[All, 2]]]

Graph[makeTree[{4, 3, 2}], VertexLabels -> "Name"]

Mathematica graphics

Side note 1: If you wonder about the argument right of the v_ in nextLevel[{v_, _}, n_], this is where we remember our resulting edges. With Fold (or FoldList) we either can do it that way or we could use Sow and Reap to send the resulting edges where we can collect them.

Side note 2: Creating a tree-structure and labeling it in pre-order is easier and can be done in fun ways. One of them is a simple call to ArrayReshape with your depth-list:

Block[{count = 1}, ArrayReshape[{}, {4, 3, 2}] /. List | 0 :> count++] // TreeForm

Mathematica graphics

$\endgroup$
1
$\begingroup$

This does what you want. Not recursive (no real need).

    maketree[spec_] := 
     Flatten[Function[edg, MapThread[Thread[#1  \[UndirectedEdge]  #2] &, 
            {First@edg, Partition[Last@edg, Length@Last@edg/Length@First@edg]}]] /@ 
       Partition[FoldList[Range[Max[#] + 1, Max[#] + 1 + Length@#*#2 - 1] &, {spec[[1]]}, 
                          Rest@spec], 2, 1]]


graph=maketree[{1, 2, 2, 2, 3}];

Graph[graph, VertexLabels -> "Name", ImagePadding -> 10]

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.