Tree from nesting levels: Difference between revisions
Content added Content deleted
m (→{{header|J}}) |
(→{{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 |
|||
⚫ | |||
NB. then we recursively merge deep boxes |
|||
⚫ | |||
NB. for consistency, if there are no integers, we box that empty list |
|||
shallow=. 2 > L."0 y |
|||
⚫ | |||
merge each group ,each//. y |
|||
⚫ | |||
dtree=: {{ |
dtree=: {{ |
||
<^:(0=L.) merge <^:]each y |
<^:(0=L.) merge <^:]each y |
||
⚫ | |||
merge=: {{ |
|||
⚫ | |||
shallow=. 2 > L."0 y NB. locate shallow 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: |
|||
⚫ | |||
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}}== |