Visualize a tree: Difference between revisions
Content added Content deleted
Line 2,737: | Line 2,737: | ||
│ |
│ |
||
└─ Lambda</pre> |
└─ Lambda</pre> |
||
=={{header|jq}}== |
|||
{{works with|jq}} |
|||
'''Works with gojq, the Go implementation of jq''' |
|||
In this entry, a tree $t is represented by an array [root, child1, |
|||
child2 ...] where root must be present and cannot be an array, and |
|||
the children, which may also be trees, may all be absent. |
|||
The tree [0, 1, 2, 3] is displayed as: |
|||
<pre> |
|||
0 |
|||
├─ 1 |
|||
├─ 2 |
|||
└─ 3 |
|||
</pre> |
|||
<lang jq># Input: a string prefix |
|||
# Output: a stream of strings representing $t |
|||
# In this implementation, empty arrays in $t are simply ignored. |
|||
def printTree: |
|||
def tidy: |
|||
sub("└─"; " ") |
|||
| sub("├─"; "| ") ; |
|||
def print($tree): |
|||
if $tree|type != "array" then . + ($tree|tostring) |
|||
else # ignore empty arrays |
|||
($tree | map(select(if type == "array" then length>0 else true end))) as $tree |
|||
| if $tree|length == 0 then empty |
|||
elif $tree|length == 1 |
|||
then print($tree[0]) |
|||
else print($tree[0]), |
|||
($tree[1:] as $children |
|||
| tidy as $p |
|||
| ($p + ( "├─" | print($children[:-1][]))), |
|||
($p + ( "└─" | print($children[-1]))) ) |
|||
end |
|||
end ; |
|||
. as $tree |
|||
| "" | print($tree) ;</lang> |
|||
'''Examples''' |
|||
<lang jq>def bigTree: |
|||
["a", |
|||
["aa", |
|||
["aaa", |
|||
["aaaa"], |
|||
["aaab", |
|||
["aaaba"], |
|||
["aaabb"]], |
|||
["aaac"]]], |
|||
["ab"], |
|||
["ac", |
|||
["aca"], |
|||
["acb"], |
|||
["acc"]]] ; |
|||
[0, 1, 2, 3], |
|||
[1,[2,3,[4, 5, [6,7,8], 9, [10,11]]]], |
|||
bigTree |
|||
| ("Tree with array representation:\n\(.)\n", |
|||
printTree, |
|||
"")</lang> |
|||
{{out}} |
|||
<pre> |
|||
Tree with array representation: |
|||
[0,1,2,3] |
|||
0 |
|||
├─1 |
|||
├─2 |
|||
└─3 |
|||
Tree with array representation: |
|||
[1,[2,3,[4,5,[6,7,8],9,[10,11]]]] |
|||
1 |
|||
└─2 |
|||
├─3 |
|||
└─4 |
|||
├─5 |
|||
├─6 |
|||
| ├─7 |
|||
| └─8 |
|||
├─9 |
|||
└─10 |
|||
└─11 |
|||
Tree with array representation: |
|||
["a",["aa",["aaa",["aaaa"],["aaab",["aaaba"],["aaabb"]],["aaac"]]],["ab"],["ac",["aca"],["acb"],["acc"]]] |
|||
a |
|||
├─aa |
|||
| └─aaa |
|||
| ├─aaaa |
|||
| ├─aaab |
|||
| | ├─aaaba |
|||
| | └─aaabb |
|||
| └─aaac |
|||
├─ab |
|||
└─ac |
|||
├─aca |
|||
├─acb |
|||
└─acc |
|||
</pre> |
|||
=={{header|Julia}}== |
=={{header|Julia}}== |