Suffix tree: Difference between revisions

J: partial bugfix
(J)
(J: partial bugfix)
Line 127:
 
<lang J>classify=: {.@> </. ]
 
root=: ,:__;_;''
 
build_tree=:3 :0
if. 0=#y do. i.0 3 return.end.
root=:. ,:___;_;''
if. 1=#y do. root,(#;y);0;y return.end.
tree=. root
for_box.classify y do.
char=. {.>{.>box
subtree=. }.build_tree }.each>box
ndx=.I.0=1&{::"1 subtree
ifn=. 1=#ndx do.tree
if. 1=#ndx do.
tree=. tree, (]1+&.>{.)`0:`]}~"1 subtree ndx}~ char ((,L:0 {:)`2:`])} {.ndx{subtree
counts=. 1 + 0&{::"1 subtree
else.
parents=. (0>.n-1) (+**&*) 1&{::"1 subtree
n=.#tree
treeedges=. tree,(__;0;,ndx}~ <@(char),(1;n;0ndx&{::)) + ::]2&.>{"1 subtree
tree=. tree, counts;"0 1 parents;"0 edges
end.
else.
tree=. tree,(__;0;,char),(1;n;0) + ::]&.>"1 subtree
end.
end.
)
 
suffix_tree=:3 :0
assert. -.({:e.}:)y
Line 155 ⟶ 157:
Task example:
 
<lang J> suffix_tree 'banana$'
┌──┬───────┬─┬──┬───┬─┬─┬──┬───┬─┬─┐
┌─┬───────┬─┬──┬───┬─┬─┬──┬───┬─┬─┐
│_│1│__│1 │_│_ │2 │4│6│_ │3 │5│7│
├──┼───────┼─┼──┼───┼─┼─┼──┼───┼─┼─┤
├─┼───────┼─┼──┼───┼─┼─┼──┼───┼─┼─┤
│_│0│_ │0 │0│2 │3│2 │3│2│0│2│2│0 │1│7 │1│0││7│0│
├──┼───────┼─┼──┼───┼─┼─┼──┼───┼─┼─┤
├─┼───────┼─┼──┼───┼─┼─┼──┼───┼─┼─┤
│banana$│a│na│na$│$│$│na│na$│$│$│
└──┴───────┴─┴──┴───┴─┴─┴──┴───┴─┴─┘</lang>
└─┴───────┴─┴──┴───┴─┴─┴──┴───┴─┴─┘</lang>
 
The first row is the leaf number (_ for internal nodes).
6,962

edits