-
Notifications
You must be signed in to change notification settings - Fork 0
/
longest_common_prefix.sf
51 lines (44 loc) · 1.04 KB
/
longest_common_prefix.sf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/ruby
#
## https://rosettacode.org/wiki/Longest_common_prefix#Sidef
#
# Finds the first point where the tree bifurcates
func find_common_prefix(hash, acc) {
if (hash.len == 1) {
var pair = hash.to_a[0]
return __FUNC__(pair.value, acc+pair.key)
}
return acc
}
# Creates a tree like: {a => {b => {c => {}}}}
func lcp(*strings) {
var hash = Hash()
for str in (strings.sort_by{.len}) {
var ref = hash
str.is_empty && return ''
for char in str {
if (ref.contains(char)) {
ref = ref{char}
ref.len == 0 && break
}
else {
ref = (ref{char} = Hash())
}
}
}
return find_common_prefix(hash, '')
}
var data = [
["interspecies","interstellar","interstate"],
["throne","throne"],
["throne","dungeon"],
["throne","","throne"],
["cheese"],
[""],
[],
["prefix","suffix"],
["foo","foobar"]
];
data.each { |set|
say "lcp(#{set.dump.substr(1,-1)}) = #{lcp(set...).dump}";
}