Longest common suffix: Difference between revisions

Added Easylang
(Added 11l)
(Added Easylang)
 
(27 intermediate revisions by 21 users not shown)
Line 9:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">F lcs(sa)
I sa.empty
R ‘’
Line 28:
print(lcs([‘Sunday’, ‘Monday’, ‘Tuesday’]))
print(lcs([‘Sunday’, ‘Monday’, ‘Tuesday’, ‘day’]))
print(lcs([‘Sondag’, ‘Maandag’, ‘Dinsdag’, ‘Woensdag’]))</langsyntaxhighlight>
 
{{out}}
Line 36:
day
dag
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">DEFINE PTR="CARD"
 
BYTE Func Equals(CHAR ARRAY a,b)
BYTE i
 
IF a(0)#b(0) THEN
RETURN (0)
FI
 
FOR i=1 TO a(0)
DO
IF a(i)#b(i) THEN
RETURN (0)
FI
OD
RETURN (1)
 
BYTE FUNC CommonLength(PTR ARRAY texts BYTE count)
CHAR ARRAY t
BYTE i,len
 
IF count=0 THEN
RETURN (0)
FI
 
len=255
FOR i=0 TO count-1
DO
t=texts(i)
IF t(0)<len THEN
len=t(0)
FI
OD
RETURN (len)
 
PROC Suffix(PTR ARRAY texts BYTE count CHAR ARRAY res)
CHAR ARRAY t(100)
CHAR ARRAY tmp
BYTE i,len,found
 
IF count=1 THEN
SCopy(res,texts(0))
RETURN
FI
 
len=CommonLength(texts,count)
WHILE len>0
DO
tmp=texts(0)
SCopyS(res,tmp,tmp(0)-len+1,tmp(0))
found=1
FOR i=1 TO count-1
DO
tmp=texts(i)
SCopyS(t,texts(i),tmp(0)-len+1,tmp(0))
IF Equals(res,t)#1 THEN
found=0 EXIT
FI
OD
IF found THEN
RETURN
FI
len==-1
OD
res(0)=0
RETURN
 
PROC Test(PTR ARRAY texts BYTE count)
BYTE i
CHAR ARRAY res(100)
 
Suffix(texts,count,res)
Print("lcs(")
IF count>0 THEN
FOR i=0 TO count-1
DO
PrintF("""%S""",texts(i))
IF i<count-1 THEN
Print(",")
FI
OD
FI
PrintF(")=""%S""%E",res)
RETURN
 
PROC Main()
CHAR ARRAY
t1="Sunday", t2="Monday", t3="Tuesday", t4="Wednesday",
t5="Thursday", t6="Friday", t7="Saturday",
t8="throne", t9="throne", t10="dungeon", t11="",
t12="prefix", t13="suffix"
PTR ARRAY texts(20)
 
texts(0)=t1 texts(1)=t2 texts(2)=t3
texts(3)=t4 texts(4)=t5 texts(5)=t6
texts(6)=t7
Test(texts,7)
 
texts(0)=t8 texts(1)=t9
Test(texts,2)
 
texts(0)=t8 texts(1)=t10
Test(texts,2)
 
texts(0)=t8 texts(1)=t11 texts(2)=t9
Test(texts,3)
 
texts(0)=t10
Test(texts,1)
 
texts(0)=t11
Test(texts,1)
 
Test(texts,0)
 
texts(0)=t12 texts(1)=t13
Test(texts,2)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Longest_common_suffix.png Screenshot from Atari 8-bit computer]
<pre>
lcs("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")="day"
lcs("throne","throne")="throne"
lcs("throne","dungeon")=""
lcs("throne","","throne")=""
lcs("dungeon")="dungeon"
lcs("")=""
lcs()=""
lcs("prefix","suffix")="fix"
</pre>
 
=={{header|Ada}}==
<syntaxhighlight lang="ada">with Ada.Strings.Unbounded;
with Ada.Text_Io.Unbounded_IO;
 
procedure Longest_Common_Suffix is
use Ada.Text_Io;
use Ada.Text_Io.Unbounded_Io;
use Ada.Strings.Unbounded;
 
subtype Ustring is Unbounded_String;
 
function "+"(S : String) return Ustring
renames To_Unbounded_String;
 
type String_List is array (Positive range <>) of Ustring;
 
function Longest_Suffix (List : String_List) return Ustring is
Suffix : Ustring := List (List'First);
begin
for A in List'First + 1 .. List'Last loop
declare
Word : Ustring renames List (A);
Found : Boolean := False;
Len : constant Natural :=
Natural'Min (Length (Suffix), Length (Word));
begin
for P in reverse 1 .. Len loop
if Tail (Suffix, P) = Tail (Word, P) then
Suffix := Tail (Word, P);
Found := True;
exit;
end if;
end loop;
if not Found then
Suffix := +"";
end if;
end;
end loop;
return Suffix;
end Longest_Suffix;
 
procedure Put (List : String_List) is
begin
Put ("[");
for S of List loop
Put ("'"); Put (S); Put ("' ");
end loop;
Put ("]");
end Put;
 
procedure Test (List : String_List) is
begin
Put (List); Put (" -> '");
Put (Longest_Suffix (List));
Put ("'");
New_Line;
end Test;
 
Case_1 : constant String_List := (+"baabababc", +"baabc", +"bbbabc");
Case_2 : constant String_List := (+"baabababc", +"baabc", +"bbbazc");
Case_3 : Constant String_List := (+"Sunday", +"Monday", +"Tuesday",
+"Wednesday", +"Thursday", +"Friday",
+"Saturday");
Case_4 : constant String_List := (+"longest", +"common", +"suffix");
Case_5 : constant String_List := (1 => +"suffix");
Case_6 : Constant String_List := (1 => +"");
begin
Test (Case_1);
Test (Case_2);
Test (Case_3);
Test (Case_4);
Test (Case_5);
Test (Case_6);
end Longest_Common_Suffix;</syntaxhighlight>
{{out}}
<pre>
['baabababc' 'baabc' 'bbbabc' ] -> 'abc'
['baabababc' 'baabc' 'bbbazc' ] -> 'c'
['Sunday' 'Monday' 'Tuesday' 'Wednesday' 'Thursday' 'Friday' 'Saturday' ] -> 'day'
['longest' 'common' 'suffix' ] -> ''
['suffix' ] -> 'suffix'
['' ] -> ''
</pre>
 
Line 41 ⟶ 257:
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
Based on the Algol 68 sample for the Longest Common Prefix task.
<langsyntaxhighlight lang="algol68"># find the longest common suffix of two strings #
PRIO COMMONSUFFIX = 1;
OP COMMONSUFFIX = ( STRING a, b )STRING:
Line 104 ⟶ 320:
test suffix( ( "prefix", "suffix" ), "fix" );
test suffix( ( "send", "lend" ), "end" )
END</langsyntaxhighlight>
{{out}}
<pre>
Line 116 ⟶ 332:
longest common suffix of ( "prefix" "suffix" ) is: "fix" as expected
longest common suffix of ( "send" "lend" ) is: "end" as expected
</pre>
 
=={{header|APL}}==
{{works with|Dyalog APL}}
<syntaxhighlight lang="apl">lcs ← ⌽+/∘(∧\)∘⊃∘(∧/2=/(⌊/≢¨)↑¨⌽¨)↑⌽∘⊃</syntaxhighlight>
{{out}}
<pre> lcs 'baabababc' 'baabc' 'bbbabc'
abc
lcs 'baabababc' 'baabc' 'bbbazc'
c
lcs 'Sunday' 'Monday' 'Tuesday' 'Wednesday' 'Thursday' 'Friday' 'Saturday'
day
lcs 'longest' 'common' 'suffix'
 
lcs ,⊂''
 
</pre>
 
Line 124 ⟶ 356:
The simplest solution in AppleScript seems to be to reverse the strings, apply the [https://www.rosettacode.org/wiki/Longest_common_prefix#AppleScriptObjC AppleScriptObjC] solution for the [https://www.rosettacode.org/wiki/Longest_common_prefix Longest common prefix] task, and reverse the result.
 
<langsyntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
 
Line 168 ⟶ 400:
longestCommonSuffix({"prefix", "suffix"}) --> "fix"
longestCommonSuffix({"remark", "spark", "aardvark"}) --> "ark"
longestCommonSuffix({"ectoplasm", "banana"}) --> ""</langsyntaxhighlight>
 
===Functional===
and for more productivity, and higher re-use of library functions, we can write a functional definition (rather than a procedure):
 
<langsyntaxhighlight lang="applescript">------------------- LONGEST COMMON SUFFIX ------------------
 
 
Line 508 ⟶ 740:
set my text item delimiters to dlm
str
end unlines</langsyntaxhighlight>
{{Out}}
<pre>['throne', 'sousaphone', 'tone'] -> 'one'
Line 514 ⟶ 746:
['remark', 'spark', 'aardvark', 'lark'] -> 'ark'
['ectoplasm', 'banana', 'brick'] -> ''</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">lcs: function [l][
ret: ""
idx: 0
 
lst: map l => reverse
while [true] [
thisLetter: ""
loop lst 'word [
if idx=size word -> return reverse ret
if thisLetter="" -> thisLetter: get split word idx
if thisLetter<>get split word idx -> return reverse ret
]
ret: ret ++ thisLetter
idx: idx + 1
]
]
 
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|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Longest_common_suffix(data){
for num, v in StrSplit(data.1)
for i, word in data
Line 522 ⟶ 788:
return num=1 ? "" : SubStr(word, 2-num)
return SubStr(word, 1-num)
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % ""
. "`n" Longest_common_suffix(["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"])
. "`n" Longest_common_suffix(["throne", "throne"])
Line 532 ⟶ 798:
. "`n" Longest_common_suffix(["prefix", "suffix"])
. "`n" Longest_common_suffix(["bar", "foobar"])
return</langsyntaxhighlight>
{{out}}
<pre>day
Line 542 ⟶ 808:
fix
bar</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f LONGEST_COMMON_SUFFIX.AWK
BEGIN {
arr1[++n1] = "AAbcd,Abcd,abcd,bcd"
arr1[++n1] = "11Sunday,2Sunday"
arr1[++n1] = "Sunday,Monday"
arr1[++n1] = "Sunday,Monday,day"
arr1[++n1] = "Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday"
arr1[++n1] = "crucifix,infix,prefix,suffix"
arr1[++n1] = "identical,identical"
arr1[++n1] = ","
arr1[++n1] = "this,has,nothing,in,common"
for (i=1; i<=n1; i++) {
n2 = split(arr1[i],arr2,",")
min_wid = 999
for (j=1; j<=n2; j++) {
leng = length(arr2[j])
if (min_wid > leng) {
min_wid = leng
min_col = j
}
}
cols = 0
for (j=1; j<=min_wid; j++) {
delete arr3
for (k=1; k<n2; k++) {
arr3[substr(arr2[k],length(arr2[k])+1-j)] = ""
arr3[substr(arr2[k+1],length(arr2[k+1])+1-j)] = ""
}
if (length(arr3) == 1) {
cols++
}
}
printf("'%s' : '%s'\n",arr1[i],(cols == 0) ? "" : substr(arr2[min_col],length(arr2[min_col])+1-cols))
}
exit(0)
}
</syntaxhighlight>
{{out}}
<pre>
'AAbcd,Abcd,abcd,bcd' : 'bcd'
'11Sunday,2Sunday' : 'Sunday'
'Sunday,Monday' : 'nday'
'Sunday,Monday,day' : 'day'
'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday' : 'day'
'crucifix,infix,prefix,suffix' : 'fix'
'identical,identical' : 'identical'
',' : ''
'this,has,nothing,in,common' : ''
</pre>
 
=={{header|BaCon}}==
<langsyntaxhighlight BaConlang="bacon">FUNCTION Common_Suffix$(data$)
 
LOCAL x, size
Line 566 ⟶ 884:
PRINT "The common suffix is: '", Common_Suffix$("longest common suffix"), "'"
PRINT "The common suffix is: '", Common_Suffix$("prefix suffix"), "'"
PRINT "The common suffix is: '", Common_Suffix$(""), "'"</langsyntaxhighlight>
{{out}}
<pre>The common suffix is: 'abc'
Line 573 ⟶ 891:
The common suffix is: 'fix'
The common suffix is: ''</pre>
 
=={{header|C}}==
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
typedef struct node_t {
char *elem;
int length;
struct node_t *next;
} node;
 
node *make_node(char *s) {
node *t = malloc(sizeof(node));
t->elem = s;
t->length = strlen(s);
t->next = NULL;
return t;
}
 
void append_node(node *head, node *elem) {
while (head->next != NULL) {
head = head->next;
}
head->next = elem;
}
 
void print_node(node *n) {
putc('[', stdout);
while (n != NULL) {
printf("`%s` ", n->elem);
n = n->next;
}
putc(']', stdout);
}
 
char *lcs(node *list) {
int minLen = INT_MAX;
int i;
 
char *res;
node *ptr;
 
if (list == NULL) {
return "";
}
if (list->next == NULL) {
return list->elem;
}
 
for (ptr = list; ptr != NULL; ptr = ptr->next) {
minLen = min(minLen, ptr->length);
}
if (minLen == 0) {
return "";
}
 
res = "";
for (i = 1; i < minLen; i++) {
char *suffix = &list->elem[list->length - i];
 
for (ptr = list->next; ptr != NULL; ptr = ptr->next) {
char *e = &ptr->elem[ptr->length - i];
if (strcmp(suffix, e) != 0) {
return res;
}
}
 
res = suffix;
}
 
return res;
}
 
void test(node *n) {
print_node(n);
printf(" -> `%s`\n", lcs(n));
}
 
void case1() {
node *n = make_node("baabababc");
append_node(n, make_node("baabc"));
append_node(n, make_node("bbbabc"));
test(n);
}
 
void case2() {
node *n = make_node("baabababc");
append_node(n, make_node("baabc"));
append_node(n, make_node("bbbazc"));
test(n);
}
 
void case3() {
node *n = make_node("Sunday");
append_node(n, make_node("Monday"));
append_node(n, make_node("Tuesday"));
append_node(n, make_node("Wednesday"));
append_node(n, make_node("Thursday"));
append_node(n, make_node("Friday"));
append_node(n, make_node("Saturday"));
test(n);
}
 
void case4() {
node *n = make_node("longest");
append_node(n, make_node("common"));
append_node(n, make_node("suffix"));
test(n);
}
 
void case5() {
node *n = make_node("suffix");
test(n);
}
 
void case6() {
node *n = make_node("");
test(n);
}
 
int main() {
case1();
case2();
case3();
case4();
case5();
case6();
return 0;
}</syntaxhighlight>
{{out}}
<pre>[`baabababc` `baabc` `bbbabc` ] -> `abc`
[`baabababc` `baabc` `bbbazc` ] -> `c`
[`Sunday` `Monday` `Tuesday` `Wednesday` `Thursday` `Friday` `Saturday` ] -> `day`
[`longest` `common` `suffix` ] -> ``
[`suffix` ] -> `suffix`
[`` ] -> ``</pre>
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
 
std::string lcs(const std::vector<std::string>& strs) {
std::vector<std::string::const_reverse_iterator> backs;
std::string s;
if (strs.size() == 0) return "";
if (strs.size() == 1) return strs[0];
for (auto& str : strs) backs.push_back(str.crbegin());
while (backs[0] != strs[0].crend()) {
char ch = *backs[0]++;
for (std::size_t i = 1; i<strs.size(); i++) {
if (backs[i] == strs[i].crend()) goto done;
if (*backs[i] != ch) goto done;
backs[i]++;
}
s.push_back(ch);
}
done:
reverse(s.begin(), s.end());
return s;
}
 
void test(const std::vector<std::string>& strs) {
std::cout << "[";
for (std::size_t i = 0; i<strs.size(); i++) {
std::cout << '"' << strs[i] << '"';
if (i != strs.size()-1) std::cout << ", ";
}
std::cout << "] -> `" << lcs(strs) << "`\n";
}
 
int main() {
std::vector<std::string> t1 = {"baabababc", "baabc", "bbabc"};
std::vector<std::string> t2 = {"baabababc", "baabc", "bbazc"};
std::vector<std::string> t3 =
{"Sunday", "Monday", "Tuesday", "Wednesday", "Friday", "Saturday"};
std::vector<std::string> t4 = {"longest", "common", "suffix"};
std::vector<std::string> t5 = {""};
std::vector<std::string> t6 = {};
std::vector<std::string> t7 = {"foo", "foo", "foo", "foo"};
 
std::vector<std::vector<std::string>> tests = {t1,t2,t3,t4,t5,t6,t7};
for (auto t : tests) test(t);
return 0;
}</syntaxhighlight>
{{out}}
<pre>["baabababc", "baabc", "bbabc"] -> `abc`
["baabababc", "baabc", "bbazc"] -> `c`
["Sunday", "Monday", "Tuesday", "Wednesday", "Friday", "Saturday"] -> `day`
["longest", "common", "suffix"] -> ``
[""] -> ``
[] -> ``
["foo", "foo", "foo", "foo"] -> `foo`</pre>
 
=={{header|Cowgol}}==
<syntaxhighlight lang="cowgol">include "cowgol.coh";
include "strings.coh";
 
sub lcs(arr: [[uint8]], len: intptr): (s: [uint8]) is
if len == 0 then
s := "";
return;
elseif len == 1 then
s := [arr];
return;
end if;
s := [arr];
var slen := StrLen(s);
s := s + slen;
arr := @next arr;
len := len - 1;
 
while len > 0 and slen > 0 loop
var c := [arr];
var clen := StrLen(c);
c := c + clen;
if clen > slen then
clen := slen;
end if;
while clen > 0 and [c] == [s] loop
c := @prev c;
s := @prev s;
clen := clen - 1;
end loop;
slen := StrLen(s);
s := s + slen;
arr := @next arr;
len := len - 1;
end loop;
s := s - slen + 1;
end sub;
 
sub test(arr: [[uint8]], len: intptr) is
var s := arr;
var l := len;
print_char('[');
while l > 0 loop
print_char('"');
print([s]);
print_char('"');
s := @next s;
l := l - 1;
if l > 0 then
print(", ");
end if;
end loop;
print("] -> `");
print(lcs(arr, len));
print("`\n");
end sub;
 
var test1: [uint8][] := {"baabababc", "baabc", "bbbabc"};
var test2: [uint8][] := {"baabababc", "baabc", "bbbazc"};
var test3: [uint8][] :=
{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday"};
var test4: [uint8][] := {"longest", "common", "suffix"};
var test5: [uint8][] := {""};
var test6: [uint8][] := {};
 
test(&test1[0], @sizeof test1);
test(&test2[0], @sizeof test2);
test(&test3[0], @sizeof test3);
test(&test4[0], @sizeof test4);
test(&test5[0], @sizeof test5);
test(&test6[0], @sizeof test6);</syntaxhighlight>
{{out}}
<pre>["baabababc", "baabc", "bbbabc"] -> `abc`
["baabababc", "baabc", "bbbazc"] -> `c`
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] -> `day`
["longest", "common", "suffix"] -> ``
[""] -> ``
[] -> ``</pre>
 
=={{header|D}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="d">import std.algorithm;
import std.stdio;
 
Line 617 ⟶ 1,222:
writeln(test, " -> `", lcs(test), '`');
}
}</langsyntaxhighlight>
{{out}}
<pre>["baabababc", "baabc", "bbbabc"] -> `abc`
Line 630 ⟶ 1,235:
{{libheader| Types}}
{{Trans|Ring}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Longest_common_suffix;
 
Line 737 ⟶ 1,342:
end.
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 747 ⟶ 1,352:
 
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|Factor}}==
{{works with|Factor|0.99 2020-07-03}}
<langsyntaxhighlight lang="factor">USING: accessors grouping kernel prettyprint sequences
sequences.extras ;
 
Line 763 ⟶ 1,408:
{ "baabababc" "baabc" "bbbabc" } lcs .
{ "baabababc" "baabc" "bbbazc" } lcs .
{ "" } lcs .</langsyntaxhighlight>
{{out}}
<pre>
Line 770 ⟶ 1,415:
""
</pre>
 
=={{header|FreeBASIC}}==
{{trans|Ring}}
<syntaxhighlight lang="freebasic">Dim As String pre(1 To ...) = {"baabababc","baabc","bbbabc"}
Dim As Integer longitud = Ubound(pre)
Dim As Integer lenList(longitud)
Dim As Integer n, m, longest
Dim As String temp
 
Function rever(Byval text As String) As String
Dim As String text2 = text
Dim As Integer x, lt = Len(text)
For x = 0 To lt Shr 1 - 1
Swap text2[x], text2[lt - x - 1]
Next x
Return text2
End Function
 
Print "There are"; longitud; " words in the list: ";
For n = 1 To longitud
Print pre(n); " ";
temp = pre(n)
pre(n) = rever(temp)
lenList(n) = Len(pre(n))
Next n
 
For m = 1 To lenList(1)
Dim As String sub1 = Mid(pre(1),1,m)
Dim As String sub2 = Mid(pre(2),1,m)
Dim As String sub3 = Mid(pre(3),1,m)
If sub1 = sub2 And sub2 = sub3 Then longest = m
Next m
 
Dim As String longPrefix = Mid(pre(1),1,longest)
longPrefix = rever(longPrefix)
 
Print !"\n\nThe longest common suffix is: "; longPrefix
Sleep</syntaxhighlight>
{{out}}
<pre>There are 3 words in the list: baabababc baabc bbbabc
 
The longest common suffix is: abc</pre>
 
 
=={{header|Go}}==
{{trans|Wren}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 824 ⟶ 1,512:
fmt.Printf("%v -> \"%s\"\n", test, lcs(test))
}
}</langsyntaxhighlight>
 
{{out}}
Line 838 ⟶ 1,526:
=={{header|Haskell}}==
This task clearly needs a little more work to bring it up to the usual standard – it's rather underspecified, and bereft of test samples – but one response, for the moment, might be something like:
<langsyntaxhighlight lang="haskell">import Data.List (transpose)
 
longestCommonSuffix :: [String] -> String
Line 866 ⟶ 1,554:
, "dag"
]
]</langsyntaxhighlight>
{{Out}}
<pre>day
dag</pre>
 
 
=={{header|J}}==
<syntaxhighlight lang="j">lcs =: [: |. [: ({. #~ [: *./\ [: *./ 2 =/\ ]) >@(|. each)
 
test1 =: 'baabababc';'baabc';'bbabc'
test2 =: 'baabababc';'baabc';'bbazc'
test3 =: 'Sunday';'Monday';'Tuesday';'Wednesday';'Friday';'Saturday'
test4 =: 'longest';'common';'suffix'
tests =: test1;test2;test3;<test4
echo@((1{":),' -> ', 1{":@<@lcs) each tests
exit''</syntaxhighlight>
 
{{out}}
 
<pre>│baabababc│baabc│bbabc│ -> │abc│
│baabababc│baabc│bbazc│ -> │c│
│Sunday│Monday│Tuesday│Wednesday│Friday│Saturday│ -> │day│
│longest│common│suffix│ -> ││</pre>
 
=={{header|Java}}==
{{trans|Kotlin}}
<syntaxhighlight lang="java">import java.util.List;
 
public class App {
private static String lcs(List<String> a) {
var le = a.size();
if (le == 0) {
return "";
}
if (le == 1) {
return a.get(0);
}
var le0 = a.get(0).length();
var minLen = le0;
for (int i = 1; i < le; i++) {
if (a.get(i).length() < minLen) {
minLen = a.get(i).length();
}
}
if (minLen == 0) {
return "";
}
var res = "";
var a1 = a.subList(1, a.size());
for (int i = 1; i < minLen; i++) {
var suffix = a.get(0).substring(le0 - i);
for (String e : a1) {
if (!e.endsWith(suffix)) {
return res;
}
}
res = suffix;
}
return "";
}
 
public static void main(String[] args) {
var tests = List.of(
List.of("baabababc", "baabc", "bbbabc"),
List.of("baabababc", "baabc", "bbbazc"),
List.of("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"),
List.of("longest", "common", "suffix"),
List.of("suffix"),
List.of("")
);
for (List<String> test : tests) {
System.out.printf("%s -> `%s`\n", test, lcs(test));
}
}
}</syntaxhighlight>
{{out}}
<pre>[baabababc, baabc, bbbabc] -> `abc`
[baabababc, baabc, bbbazc] -> `c`
[Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday] -> `day`
[longest, common, suffix] -> ``
[suffix] -> `suffix`
[] -> ``</pre>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">(() => {
'use strict';
 
Line 1,062 ⟶ 1,827:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>Longest common suffix:
Line 1,070 ⟶ 1,835:
remark spark aardvark lark -> 'ark'
ectoplasm banana brick -> ''</pre>
 
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
This entry uses `longest_common_prefix` from [[Longest_common_suffix#jq]] and so the definition is not repeated here.
<syntaxhighlight lang="jq">
# Input: an array of strings
def longest_common_suffix:
def r: explode | reverse | implode;
if length == 0 then "" # by convention
elif length == 1 then .[0] # for speed
else map(r)
| longest_common_prefix
| r
end;</syntaxhighlight>
'''Test Cases'''
<syntaxhighlight lang="jq">def test:
["baabababc","baabc","bbbabc"],
["baabababc","baabc","bbbazc"],
[""],
[],
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
["throne","cone", "bone"]
| "\(.) => \(longest_common_suffix)";
 
test
</syntaxhighlight>
{{out}}
<pre>
["baabababc","baabc","bbbabc"] => abc
["baabababc","baabc","bbbazc"] => c
[""] =>
[] =>
["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"] => day
["throne","cone","bone"] => one
</pre>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">function longestcommonsuffix(strings)
n, nmax = 0, minimum(length, strings)
nmax == 0 && return ""
Line 1,083 ⟶ 1,885:
println(longestcommonsuffix(["baabababc","baabc","bbbabc"]))
println(longestcommonsuffix(["baabababc","baabc","bbbazc"]))
println(longestcommonsuffix([""]))</langsyntaxhighlight>{{out}}
<pre>
abc
c
 
</pre>
 
=={{header|Kotlin}}==
{{trans|Go}}
<langsyntaxhighlight lang="scala">fun lcs(a: List<String>): String {
val le = a.size
if (le == 0) {
Line 1,136 ⟶ 1,937:
println("$test -> `${lcs(test)}`")
}
}</langsyntaxhighlight>
{{out}}
<pre>[baabababc, baabc, bbbabc] -> `abc`
Line 1,144 ⟶ 1,945:
[suffix] -> `suffix`
[] -> ``</pre>
 
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">#!/bin/ksh
 
# Longest common suffix
 
# # Variables:
#
typeset -a arr1=( "Sunday" "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" )
typeset -a arr2=( "baabababc" "baabc" "bbbabc" )
typeset -a arr3=( "baabababc" "babc" "bbbabc" )
typeset -a arr4=( "longest" "common" "suffix" )
typeset -a arr5=( "suffix" )
typeset -a arr6=( "" )
 
# # Functions:
#
 
# # Function _minlenele(arr) - return the shortest element in an array
#
function _minlenele {
typeset _arr ; nameref _arr="$1"
typeset _min _i ; integer _i
 
_min=${_arr[0]}
for ((_i=1; _i<${#_arr[*]}; _i++)); do
(( ${#_arr[_i]} < ${#_min} )) && _min=${_arr[_i]}
done
echo "${_min}"
}
 
######
# main #
######
 
for array in arr1 arr2 arr3 arr4 arr5 arr6; do
nameref arr=${array}
printf "\n( %s ) -> " "${arr[*]}"
suffix=$(_minlenele arr)
for ((j=${#suffix}; j>0; j--)); do
for ((i=0; i<${#arr[*]}; i++)); do
[[ ${arr[i]%${suffix: -${j}}} == ${arr[i]} ]] && continue 2
done
printf "'%s'" ${suffix: -${j}}
break
done
typeset +n arr
done
echo
</syntaxhighlight>{{out}}
<pre>
( Sunday Monday Tuesday Wednesday Thursday Friday Saturday ) -> 'day'
( baabababc baabc bbbabc ) -> 'abc'
( baabababc babc bbbabc ) -> 'babc'
( longest common suffix ) ->
( suffix ) -> 'suffix'
( ) ->
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">ClearAll[LCS]
LCS[x_List] := Module[{l, s},
If[Length[x] > 0,
l = Min[StringLength /@ x];
s = Characters[StringTake[x, -l]];
s //= Transpose;
l = LengthWhile[Reverse@s, Apply[SameQ]];
StringTake[First[x], -l]
,
""
]
]
LCS[{"throne", "sousaphone"}]
LCS[{"prefix", "suffix"}]
LCS[{"remark", "spark", "aardvark"}]
LCS[{"throne", "", "throne"}]
LCS[{"throne", "throne"}]
LCS[{"cheese"}]
LCS[{""}]
LCS[{}]
LCS[{"ectoplasm", "banana"}]</syntaxhighlight>
{{out}}
<pre>"one"
"fix"
"ark"
""
"throne"
"cheese"
""
""
""</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import sequtils, strformat, strutils
 
func lcs(list: varargs[string]): string =
if list.len == 0: return
result = list[0]
for i in 1..list.high:
var newLength = 0
for j in 1..result.len:
if j > list[i].len or list[i][^j] != result[^j]:
break
inc newLength
result = result[^newLength..^1]
 
proc test(list: varargs[string]) =
let lst = list.mapIt('"' & it & '"').join(", ")
echo &"lcs({lst}) = \"{lcs(list)}\""
 
 
test("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
test("throne", "throne")
test("throne", "dungeon")
test("cheese")
test("")
test()
test("prefix", "suffix")
test("send", "lend")</syntaxhighlight>
 
{{out}}
<pre>lcs("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday") = "day"
lcs("throne", "throne") = "throne"
lcs("throne", "dungeon") = ""
lcs("cheese") = "cheese"
lcs("") = ""
lcs() = ""
lcs("prefix", "suffix") = "fix"
lcs("send", "lend") = "end"</pre>
 
=={{header|Perl}}==
Based on [[Longest_common_prefix]] Perl entry.
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
 
sub lcs {
for (0..$#_) { $_[$_] = join '', reverse split '', $_[$_] }
join '', reverse split '', (join("\0", @_) =~ /^ ([^\0]*) [^\0]* (?:\0 \1 [^\0]*)* $/sx)[0];
}
Line 1,165 ⟶ 2,095:
[ '' ]) {
say qq{'@$words' ==> '@{[lcs(@$words)]}';
}</langsyntaxhighlight>
 
{{out}}
Line 1,178 ⟶ 2,108:
=={{header|Phix}}==
Phix allows negative indexes, with -1 as the last element [same as $], and -length(s) the first element of s, so we can just do this:
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function longestcommonsuffix(sequence strings)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
string res = ""
<span style="color: #008080;">function</span> <span style="color: #000000;">longestcommonsuffix</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">strings</span><span style="color: #0000FF;">)</span>
if length(strings) then
<span style="color: #004080;">string</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
res = strings[1]
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">strings</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
for i=2 to length(strings) do
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">strings</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
string si = strings[i]
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">strings</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
if length(si)<length(res) then
<span style="color: #004080;">string</span> <span style="color: #000000;">si</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">strings</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
res = res[-length(si)..$]
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">si</span><span style="color: #0000FF;">)<</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
end if
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">[-</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">si</span><span style="color: #0000FF;">)..$]</span>
for j=-1 to -length(res) by -1 do
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if res[j]!=si[j] then
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #0000FF;">-</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">by</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
res = res[j+1..$]
<span style="color: #008080;">if</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]!=</span><span style="color: #000000;">si</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span>
exit
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..$]</span>
end if
<span style="color: #008080;">exit</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if length(res)=0 then exit end if
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end for
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
return res
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
sequence tests = {{"baabababc","baabc","bbbabc"},
{"baabababc","baabc","bbbazc"},
<span style="color: #004080;">sequence</span> <span style="color: #000000;">tests</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #008000;">"baabababc"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"baabc"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"bbbabc"</span><span style="color: #0000FF;">},</span>
{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"baabababc"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"baabc"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"bbbazc"</span><span style="color: #0000FF;">},</span>
{"longest", "common", "suffix"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"Sunday"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Monday"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Tuesday"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Wednesday"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Thursday"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Friday"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Saturday"</span><span style="color: #0000FF;">},</span>
{"suffix"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"longest"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"common"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"suffix"</span><span style="color: #0000FF;">},</span>
{""}}
<span style="color: #0000FF;">{</span><span style="color: #008000;">"suffix"</span><span style="color: #0000FF;">},</span>
for i=1 to length(tests) do
<span style="color: #0000FF;">{</span><span style="color: #008000;">""</span><span style="color: #0000FF;">}}</span>
printf(1,"%v ==> \"%s\"\n",{tests[i],longestcommonsuffix(tests[i])})
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
end for</lang>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%v ==&gt; \"%s\"\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">longestcommonsuffix</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,221 ⟶ 2,154:
Pending a fuller task statement and some test samples:
{{works with|Python|3}}
<langsyntaxhighlight lang="python">'''Longest common suffix'''
 
from itertools import takewhile
Line 1,270 ⟶ 2,203:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>day
dag</pre>
 
=={{header|Quackery}}==
 
<code>commonprefix</code> is defined at [[Longest common prefix#Quackery]].
 
<syntaxhighlight lang="quackery"> [ [] swap
witheach
[ reverse nested join ]
commonprefix
reverse ] is commonsuffix ( [ --> $ )
 
$ "monday tuesday wednesday thursday friday saturday sunday"
nest$ commonsuffix echo$</syntaxhighlight>
 
{{out}}
 
<pre>day</pre>
 
=={{header|Raku}}==
{{works with|Rakudo|2020.07}}
 
<syntaxhighlight lang="raku" perl6line>sub longest-common-suffix ( *@words ) {
return '' unless +@words;
my $min = @words».chars.min;
Line 1,295 ⟶ 2,245:
('one, Hey!', 'three, Hey!', 'ale, Hey!', 'me, Hey!'),
'suffix',
''</langsyntaxhighlight>
{{out}}
<pre>("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday") - LCS: >day<
Line 1,307 ⟶ 2,257:
=={{header|REXX}}==
Essentially, &nbsp; this REXX version simply reversed the strings, &nbsp; and then finds the longest common &nbsp;''prefix''.
<langsyntaxhighlight lang="rexx">/*REXX program finds the longest common suffix contained in an array of strings. */
parse arg z; z= space(z) /*obtain optional arguments from the CL*/
if z==''|z=="," then z='baabababc baabc bbbabc' /*Not specified? Then use the default.*/
Line 1,325 ⟶ 2,275:
say /*stick a fork in it, we're all done. */
if m==0 then say 'There is no common suffix.'
else say 'The longest common suffix is: ' right( word(z, 1), m)</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 1,334 ⟶ 2,284:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
 
Line 1,381 ⟶ 2,331:
next
return cStr2
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,390 ⟶ 2,340:
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>
 
=={{header|sed}}==
<syntaxhighlight lang="sed">$q
N
s/\(.*\)\(\n\).*\1$/\2\1/
D</syntaxhighlight><pre>
$ printf '%s\n' Sunday '' Monday Tuesday | sed -f suffix.sed
 
$ printf '%s\n' Sunday Monday Tuesday | sed -f suffix.sed
day
$ printf '%s\n' Sunday Monday | sed -f suffix.sed
nday
</pre>
 
=={{header|Standard ML}}==
<syntaxhighlight lang="sml">val lcs =
let
val commonSuffix = fn (s0, s1) =>
let
val rec pairTakeREq = fn (0, _) => s0 | (_, 0) => s1 | (i, j) =>
let
val i' = i - 1 and j' = j - 1
in
if String.sub (s0, i') = String.sub (s1, j')
then pairTakeREq (i', j')
else String.extract (s0, i, NONE)
end
in
pairTakeREq (size s0, size s1)
end
in
fn [] => "" | x :: xs => foldl commonSuffix x xs
end</syntaxhighlight>
 
=={{header|V (Vlang)}}==
{{trans|go}}
<syntaxhighlight lang="v (vlang)">
fn lcs(a []string) string {
// Special cases first
match a.len {
0 {
return ""
}
1 {
return a[0]
}
else {}
}
le0 := a[0].len
mut min_len := le0
for i in 1..a.len {
if a[i].len < min_len {
min_len = a[i].len
}
}
if min_len == 0 {
return ""
}
mut res := ""
a1 := a[1..]
for i := 1; i <= min_len; i++ {
suffix := a[0][le0-i..]
for e in a1 {
if e.index(suffix) or {0} + suffix.len != e.len {
return res
}
}
res = suffix
}
return res
}
// Normally something like this would be a Testlcs function in *_test.go
// and use the testing package to report failures.
fn main() {
for l in [
["baabababc", "baabc", "bbbabc"],
["baabababc", "baabc", "bbbazc"],
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
["longest", "common", "suffix"],
["suffix"],
[""],
] {
println("lcs($l) = ${lcs(l)}")
}
}</syntaxhighlight>
{{out}}
<pre>Same as Go entry</pre>
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">var lcs = Fn.new { |a|
if (a.count == 0) return ""
if (a.count == 1) return a[0]
Line 1,416 ⟶ 2,478:
[""]
]
for (test in tests) System.print("%(test) -> \"%(lcs.call(test))\"")</langsyntaxhighlight>
 
{{out}}
Line 1,426 ⟶ 2,488:
[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>
1,981

edits