Suffix tree: Difference between revisions
→{{header|Racket}}: banana now used, prettier tree output |
Go solution |
||
Line 18: | Line 18: | ||
The computation time for an efficient algorithm should be <math>O(n)</math>, but such an algorithm might be difficult to implement. An easier, <math>O(n^2)</math> algorithm is accepted. |
The computation time for an efficient algorithm should be <math>O(n)</math>, but such an algorithm might be difficult to implement. An easier, <math>O(n^2)</math> algorithm is accepted. |
||
=={{header|Go}}== |
|||
Vis function from [[Visualize_a_tree#Unicode]]. |
|||
<lang go>package main |
|||
import "fmt" |
|||
func main() { |
|||
vis(buildTree("banana$")) |
|||
} |
|||
type tree []node |
|||
type node struct { |
|||
sub string // a substring of the input string |
|||
ch []int // list of child nodes |
|||
} |
|||
func buildTree(s string) tree { |
|||
t := tree{node{}} // root node |
|||
for i := range s { |
|||
t = t.addSuffix(s[i:]) |
|||
} |
|||
return t |
|||
} |
|||
func (t tree) addSuffix(suf string) tree { |
|||
n := 0 |
|||
for i := 0; i < len(suf); { |
|||
b := suf[i] |
|||
ch := t[n].ch |
|||
var x2, n2 int |
|||
for ; ; x2++ { |
|||
if x2 == len(ch) { |
|||
// no matching child, remainder of suf becomes new node. |
|||
n2 = len(t) |
|||
t = append(t, node{sub: suf[i:]}) |
|||
t[n].ch = append(t[n].ch, n2) |
|||
return t |
|||
} |
|||
n2 = ch[x2] |
|||
if t[n2].sub[0] == b { |
|||
break |
|||
} |
|||
} |
|||
// find prefix of remaining suffix in common with child |
|||
sub2 := t[n2].sub |
|||
j := 0 |
|||
for ; j < len(sub2); j++ { |
|||
if suf[i+j] != sub2[j] { |
|||
// split n2 |
|||
n3 := n2 |
|||
// new node for the part in common |
|||
n2 = len(t) |
|||
t = append(t, node{sub2[:j], []int{n3}}) |
|||
t[n3].sub = sub2[j:] // old node loses the part in common |
|||
t[n].ch[x2] = n2 |
|||
break // continue down the tree |
|||
} |
|||
} |
|||
i += j // advance past part in common |
|||
n = n2 // continue down the tree |
|||
} |
|||
return t |
|||
} |
|||
func vis(t tree) { |
|||
if len(t) == 0 { |
|||
fmt.Println("<empty>") |
|||
return |
|||
} |
|||
var f func(int, string) |
|||
f = func(n int, pre string) { |
|||
children := t[n].ch |
|||
if len(children) == 0 { |
|||
fmt.Println("╴", t[n].sub) |
|||
return |
|||
} |
|||
fmt.Println("┐", t[n].sub) |
|||
last := len(children) - 1 |
|||
for _, ch := range children[:last] { |
|||
fmt.Print(pre, "├─") |
|||
f(ch, pre+"│ ") |
|||
} |
|||
fmt.Print(pre, "└─") |
|||
f(children[last], pre+" ") |
|||
} |
|||
f(0, "") |
|||
}</lang> |
|||
{{out}} |
|||
<pre> |
|||
┐ |
|||
├─╴ banana$ |
|||
├─┐ a |
|||
│ ├─┐ na |
|||
│ │ ├─╴ na$ |
|||
│ │ └─╴ $ |
|||
│ └─╴ $ |
|||
├─┐ na |
|||
│ ├─╴ na$ |
|||
│ └─╴ $ |
|||
└─╴ $ |
|||
</pre> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |
Revision as of 23:51, 1 March 2015
A suffix tree is a data structure commonly used in string algorithms.
Given a string S of length n, its suffix tree is a tree T such that:
- T has exactly n leaves numbered from 1 to n.
- Except for the root, every internal node has at least two children.
- Each edge of T is labelled with a non-empty substring of S.
- No two edges starting out of a node can have string labels beginning with the same character.
- The string obtained by concatenating all the string labels found on the path from the root to leaf i spells out suffix S[i..n], for i from 1 to n.
Such a tree does not exist for all strings. To ensure existence, a character that is not found in S must be appended at its end. The character '$' is traditionally used for this purpose.
For this task, build and display the suffix tree of the string "banana$". Displaying the tree can be done using the code from the visualize a tree task, but any other convenient method is accepted.
There are several ways to implement the tree data structure, for instance how edges should be labelled. Latitude is given in this matter, but notice that a simple way to do it is to label each node with the label of the edge leading to it.
The computation time for an efficient algorithm should be , but such an algorithm might be difficult to implement. An easier, algorithm is accepted.
Go
Vis function from Visualize_a_tree#Unicode. <lang go>package main
import "fmt"
func main() {
vis(buildTree("banana$"))
}
type tree []node
type node struct {
sub string // a substring of the input string ch []int // list of child nodes
}
func buildTree(s string) tree {
t := tree{node{}} // root node for i := range s { t = t.addSuffix(s[i:]) } return t
}
func (t tree) addSuffix(suf string) tree {
n := 0 for i := 0; i < len(suf); { b := suf[i] ch := t[n].ch var x2, n2 int for ; ; x2++ { if x2 == len(ch) { // no matching child, remainder of suf becomes new node. n2 = len(t) t = append(t, node{sub: suf[i:]}) t[n].ch = append(t[n].ch, n2) return t } n2 = ch[x2] if t[n2].sub[0] == b { break } } // find prefix of remaining suffix in common with child sub2 := t[n2].sub j := 0 for ; j < len(sub2); j++ { if suf[i+j] != sub2[j] { // split n2 n3 := n2 // new node for the part in common n2 = len(t) t = append(t, node{sub2[:j], []int{n3}}) t[n3].sub = sub2[j:] // old node loses the part in common t[n].ch[x2] = n2 break // continue down the tree } } i += j // advance past part in common n = n2 // continue down the tree } return t
}
func vis(t tree) {
if len(t) == 0 { fmt.Println("<empty>") return } var f func(int, string) f = func(n int, pre string) { children := t[n].ch if len(children) == 0 { fmt.Println("╴", t[n].sub) return } fmt.Println("┐", t[n].sub) last := len(children) - 1 for _, ch := range children[:last] { fmt.Print(pre, "├─") f(ch, pre+"│ ") } fmt.Print(pre, "└─") f(children[last], pre+" ") } f(0, "")
}</lang>
- Output:
┐ ├─╴ banana$ ├─┐ a │ ├─┐ na │ │ ├─╴ na$ │ │ └─╴ $ │ └─╴ $ ├─┐ na │ ├─╴ na$ │ └─╴ $ └─╴ $
Perl
<lang Perl>use strict; use warnings; use Data::Dumper;
sub classify {
my ($f, $h) = (shift, {}); for (@_) { push @{$h->{$f->($_)}}, $_ } return $h;
} sub suffixes {
my $str = shift; map { substr $str, $_ } 0 .. length($str) - 1;
} sub suffix_tree {
return +{} if @_ == 0; return +{ $_[0] => +{} } if @_ == 1; my $h = {}; my $classif = classify sub { substr shift, 0, 1 }, @_; for my $key (sort keys %$classif) { my $subtree = suffix_tree( grep "$_", map { substr $_, 1 } @{$classif->{$key}} ); my @subkeys = keys %$subtree; if (@subkeys == 1) { my $subkey = shift @subkeys; $h->{"$key$subkey"} = $subtree->{$subkey}; } else { $h->{$key} = $subtree } } return $h;
}
print +Dumper suffix_tree suffixes 'banana$';</lang>
- Output:
$VAR1 = { '$' => {}, 'a' => { '$' => {}, 'na' => { 'na$' => {}, '$' => {} } }, 'banana$' => {}, 'na' => { 'na$' => {}, '$' => {} } };
Perl 6
Here is quite a naive algorithm, probably .
<lang Perl 6>multi suffix-tree(Str $str) { suffix-tree map &flip, [\~] $str.flip.comb } multi suffix-tree(@a) {
hash @a == 0 ?? () !! @a == 1 ?? @a[0] => [] !! gather for @a.classify(*.substr(0, 1)) { my $subtree = suffix-tree(grep *.chars, map *.substr(1), .value[]); if $subtree == 1 { my $pair = $subtree.pick; take .key ~ $pair.key => $pair.value; } else { take .key => $subtree; } }
}</lang>
Displaying the tree is done with the code from visualize a tree: <lang Perl 6>my $tree = root => suffix-tree 'banana$'; .say for visualize-tree $tree, *.key, *.value.list;</lang>
- Output:
root ├─$ ├─a │ ├─$ │ └─na │ ├─$ │ └─na$ ├─na │ ├─$ │ └─na$ └─banana$
Racket
See Suffix trees with Ukkonen’s algorithm by Danny Yoo for more information on how to use suffix trees in Racket.
<lang racket>#lang racket (require (planet dyoo/suffixtree)) (define tree (make-tree)) (tree-add! tree (string->label "banana$"))
(define (show-node nd dpth)
(define children (node-children nd)) (printf "~a~a ~a~%" (match dpth [(regexp #px"(.*) $" (list _ d)) (string-append d "`")] [else else]) (if (null? children) "--" "-+") (label->string (node-up-label nd))) (let l ((children children)) (match children ((list) (void)) ((list c) (show-node c (string-append dpth " "))) ((list c ct ...) (show-node c (string-append dpth " |")) (l ct)))))
(show-node (tree-root tree) "")</lang>
- Output:
-+ |-- $ |-+ a | |-- $ | `-+ na | |-- $ | `-- na$ |-+ na | |-- $ | `-- na$ `-- banana$