Tree from nesting levels: Difference between revisions

Content added Content deleted
(→‎{{header|J}}: flesh things out a little bit)
Line 1,057: Line 1,057:
Anyways, here's an interpretation which might be close enough to the task description:
Anyways, here's an interpretation which might be close enough to the task description:


<lang J>NB. first we nest each integer to the required depth, independently
<lang J>merge=: {{
NB. then we recursively merge deep boxes
if.(0=#$y)+.2>L.y do.y return.end.
NB. for consistency, if there are no integers, we box that empty list
shallow=. 2 > L."0 y
group=. shallow} (+/\ shallow),:-#\y
merge each group ,each//. y
}}

dtree=: {{
dtree=: {{
<^:(0=L.) merge <^:]each y
<^:(0=L.) merge <^:]each y
}}

merge=: {{
if.(0=#$y)+.2>L.y do.y return.end. NB. done if no deep boxes left
shallow=. 2 > L."0 y NB. locate shallow boxes
group=. shallow} (+/\ shallow),:-#\y NB. find groups of adjacent deep boxes
merge each group ,each//. y NB. combine them and recursively merge their contents
}}</lang>
}}</lang>


Line 1,126: Line 1,129:
│└─────────┴─┴─┴─────────┘│
│└─────────┴─┴─┴─────────┘│
└─────────────────────────┘</lang>
└─────────────────────────┘</lang>

Note that merge does not concern itself with the contents of boxes, only their nesting depth. This means that we could replace the implementation of dtree with some similar mechanism if we wished to use this approach with something else. For example:

<lang J> t=: ;:'(a b c) d (e f g)'
p=: ;:'()'
d=: +/\-/p=/t
k=: =/p=/t
merge d <@]^:[&.>&(k&#) t
┌───────┬─┬───────┐
│┌─┬─┬─┐│d│┌─┬─┬─┐│
││a│b│c││ ││e│f│g││
│└─┴─┴─┘│ │└─┴─┴─┘│
└───────┴─┴───────┘</lang>

Or, generalizing:

<lang J>pnest=: {{
t=. ;:y
p=. ;:'()'
d=: +/\-/p=/t
k=: =/p=/t
merge d <@]^:[&.>&(k&#) t
}}</lang>

Example use:

<lang J> pnest '((a b) c (d e) f) g (h i)'
┌─────────────────┬─┬─────┐
│┌─────┬─┬─────┬─┐│g│┌─┬─┐│
││┌─┬─┐│c│┌─┬─┐│f││ ││h│i││
│││a│b││ ││d│e││ ││ │└─┴─┘│
││└─┴─┘│ │└─┴─┘│ ││ │ │
│└─────┴─┴─────┴─┘│ │ │
└─────────────────┴─┴─────┘</lang>


=={{header|Julia}}==
=={{header|Julia}}==