Longest common suffix: Difference between revisions
Content deleted Content added
add sed |
Add ed example |
||
(4 intermediate revisions by 4 users not shown) | |||
Line 1,353:
Longest common suffix = abc
</pre>
=={{header|EasyLang}}==
<syntaxhighlight>
func$ right s$ i .
return substr s$ (len s$ - i + 1) i
.
func$ lcs list$[] .
if len list$[] = 0
return ""
.
ref$ = list$[1]
for s$ in list$[]
if len s$ < len ref$
ref$ = s$
.
.
for i = 1 to len ref$
sub$ = right ref$ i
for s$ in list$[]
if right s$ i <> sub$
return right ref$ (i - 1)
.
.
.
return ref$
.
print lcs [ "Sunday" "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" ]
print lcs [ "throne" "throne" ]
print lcs [ "throne" "dungeon" ]
print lcs [ "cheese" ]
print lcs [ "prefix" "suffix" ]
</syntaxhighlight>
{{out}}
<pre>
day
throne
cheese
fix
</pre>
=={{header|ed}}==
Partially inspired by [[#sed]] solution.
<syntaxhighlight lang="sed">
H
g/.*/s//&|/
,j
g/\([^|]*\)|\([^|]*\1|\)*$/s//&: \1/
,p
Q
</syntaxhighlight>
{{out}}
<pre>$ ed -s longest-suffix.input < longest-suffix.ed
Newline appended
Sunday|Monday|Tuesday|: day</pre>
=={{header|Factor}}==
Line 1,375 ⟶ 1,434:
""
</pre>
=={{header|FreeBASIC}}==
Line 2,300 ⟶ 2,358:
bbbabc
Longest common suffix = abc
</pre>
=={{header|Ruby}}==
Testcases taken from Go.
<syntaxhighlight lang="ruby">tests = [["baabababc", "baabc", "bbbabc"],
["baabababc", "baabc", "bbbazc"],
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
["longest", "common", "suffix"],
["suffix"],
[""],
]
def lcs(ar)
i = (0..ar.first.size).detect{|s| ar.all?{|word| word.end_with? ar.first[s..-1]} }
ar.first[i..-1]
end
tests.each{|test| p lcs(test) }
</syntaxhighlight>
{{out}}
<pre>"abc"
"c"
"day"
""
"suffix"
""
</pre>
Line 2,391 ⟶ 2,473:
=={{header|Wren}}==
<syntaxhighlight lang="
if (a.count == 0) return ""
if (a.count == 1) return a[0]
Line 2,425 ⟶ 2,507:
[suffix] -> "suffix"
[] -> ""
</pre>
=={{header|XPL0}}==
<syntaxhighlight lang "XPL0">include xpllib; \for StrRev
proc LCS(N, Strs); \Show longest common suffix
int N; char Strs;
int I, J, C;
[for I:= 0 to N-1 do \work with reversed strings
StrRev(@Strs(I,0));
J:= 0;
loop [C:= Strs(0,J);
if C = 0 then quit;
for I:= 1 to N-1 do
if Strs(I,J) # C then quit;
J:= J+1;
];
ChOut(0, ^");
for I:= J-1 downto 0 do
ChOut(0, Strs(0,I));
ChOut(0, ^");
CrLf(0);
for I:= 0 to N-1 do \undo reversal (for extra credit?)
StrRev(@Strs(I,0));
];
int Tests, I;
[Tests:= [
[3, "baabababc","baabc","bbbabc"],
[3, "baabababc","baabc","bbbazc"],
[7, "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
[3, "longest", "common", "suffix"],
[1, "suffix"],
[1, ""] ];
for I:= 0 to 6-1 do
LCS(Tests(I,0), @Tests(I,1));
]</syntaxhighlight>
{{out}}
<pre>
"abc"
"c"
"day"
""
"suffix"
""
</pre>
|