Longest common suffix: Difference between revisions

Added Easylang
(Longest common suffix en FreeBASIC)
(Added Easylang)
 
(8 intermediate revisions by 8 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 39:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">DEFINE PTR="CARD"
 
BYTE Func Equals(CHAR ARRAY a,b)
Line 156:
texts(0)=t12 texts(1)=t13
Test(texts,2)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Longest_common_suffix.png Screenshot from Atari 8-bit computer]
Line 171:
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Strings.Unbounded;
with Ada.Text_Io.Unbounded_IO;
 
Line 243:
Test (Case_5);
Test (Case_6);
end Longest_Common_Suffix;</langsyntaxhighlight>
{{out}}
<pre>
Line 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 320:
test suffix( ( "prefix", "suffix" ), "fix" );
test suffix( ( "send", "lend" ), "end" )
END</langsyntaxhighlight>
{{out}}
<pre>
Line 336:
=={{header|APL}}==
{{works with|Dyalog APL}}
<langsyntaxhighlight lang="apl">lcs ← ⌽+/∘(∧\)∘⊃∘(∧/2=/(⌊/≢¨)↑¨⌽¨)↑⌽∘⊃</langsyntaxhighlight>
{{out}}
<pre> lcs 'baabababc' 'baabc' 'bbbabc'
Line 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 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 740:
set my text item delimiters to dlm
str
end unlines</langsyntaxhighlight>
{{Out}}
<pre>['throne', 'sousaphone', 'tone'] -> 'one'
Line 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 754 ⟶ 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 764 ⟶ 798:
. "`n" Longest_common_suffix(["prefix", "suffix"])
. "`n" Longest_common_suffix(["bar", "foobar"])
return</langsyntaxhighlight>
{{out}}
<pre>day
Line 774 ⟶ 808:
fix
bar</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f LONGEST_COMMON_SUFFIX.AWK
BEGIN {
Line 812 ⟶ 847:
exit(0)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 827 ⟶ 862:
 
=={{header|BaCon}}==
<langsyntaxhighlight BaConlang="bacon">FUNCTION Common_Suffix$(data$)
 
LOCAL x, size
Line 849 ⟶ 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 858 ⟶ 893:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 985 ⟶ 1,020:
case6();
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>[`baabababc` `baabc` `bbbabc` ] -> `abc`
Line 995 ⟶ 1,030:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <string>
#include <vector>
Line 1,047 ⟶ 1,082:
for (auto t : tests) test(t);
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>["baabababc", "baabc", "bbabc"] -> `abc`
Line 1,058 ⟶ 1,093:
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
include "strings.coh";
 
Line 1,135 ⟶ 1,170:
test(&test4[0], @sizeof test4);
test(&test5[0], @sizeof test5);
test(&test6[0], @sizeof test6);</langsyntaxhighlight>
{{out}}
<pre>["baabababc", "baabc", "bbbabc"] -> `abc`
Line 1,146 ⟶ 1,181:
=={{header|D}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="d">import std.algorithm;
import std.stdio;
 
Line 1,187 ⟶ 1,222:
writeln(test, " -> `", lcs(test), '`');
}
}</langsyntaxhighlight>
{{out}}
<pre>["baabababc", "baabc", "bbbabc"] -> `abc`
Line 1,200 ⟶ 1,235:
{{libheader| Types}}
{{Trans|Ring}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Longest_common_suffix;
 
Line 1,307 ⟶ 1,342:
end.
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,317 ⟶ 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 1,333 ⟶ 1,408:
{ "baabababc" "baabc" "bbbabc" } lcs .
{ "baabababc" "baabc" "bbbazc" } lcs .
{ "" } lcs .</langsyntaxhighlight>
{{out}}
<pre>
Line 1,340 ⟶ 1,415:
""
</pre>
 
 
=={{header|FreeBASIC}}==
{{trans|Ring}}
<langsyntaxhighlight lang="freebasic">Dim As String pre(1 To ...) = {"baabababc","baabc","bbbabc"}
Dim As Integer longitud = Ubound(pre)
Dim As Integer lenList(longitud)
Line 1,378 ⟶ 1,452:
 
Print !"\n\nThe longest common suffix is: "; longPrefix
Sleep</langsyntaxhighlight>
{{out}}
<pre>There are 3 words in the list: baabababc baabc bbbabc
Line 1,387 ⟶ 1,461:
=={{header|Go}}==
{{trans|Wren}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,438 ⟶ 1,512:
fmt.Printf("%v -> \"%s\"\n", test, lcs(test))
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,452 ⟶ 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 1,480 ⟶ 1,554:
, "dag"
]
]</langsyntaxhighlight>
{{Out}}
<pre>day
Line 1,487 ⟶ 1,561:
 
=={{header|J}}==
<langsyntaxhighlight lang="j">lcs =: [: |. [: ({. #~ [: *./\ [: *./ 2 =/\ ]) >@(|. each)
 
test1 =: 'baabababc';'baabc';'bbabc'
Line 1,495 ⟶ 1,569:
tests =: test1;test2;test3;<test4
echo@((1{":),' -> ', 1{":@<@lcs) each tests
exit''</langsyntaxhighlight>
 
{{out}}
Line 1,506 ⟶ 1,580:
=={{header|Java}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="java">import java.util.List;
 
public class App {
Line 1,554 ⟶ 1,628:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>[baabababc, baabc, bbbabc] -> `abc`
Line 1,564 ⟶ 1,638:
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">(() => {
'use strict';
 
Line 1,753 ⟶ 1,827:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>Longest common suffix:
Line 1,767 ⟶ 1,841:
 
This entry uses `longest_common_prefix` from [[Longest_common_suffix#jq]] and so the definition is not repeated here.
<syntaxhighlight lang="jq">
<lang jq>
# Input: an array of strings
def longest_common_suffix:
Line 1,776 ⟶ 1,850:
| longest_common_prefix
| r
end;</langsyntaxhighlight>
'''Test Cases'''
<langsyntaxhighlight lang="jq">def test:
["baabababc","baabc","bbbabc"],
["baabababc","baabc","bbbazc"],
Line 1,788 ⟶ 1,862:
 
test
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,800 ⟶ 1,874:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">function longestcommonsuffix(strings)
n, nmax = 0, minimum(length, strings)
nmax == 0 && return ""
Line 1,811 ⟶ 1,885:
println(longestcommonsuffix(["baabababc","baabc","bbbabc"]))
println(longestcommonsuffix(["baabababc","baabc","bbbazc"]))
println(longestcommonsuffix([""]))</langsyntaxhighlight>{{out}}
<pre>
abc
Line 1,819 ⟶ 1,893:
=={{header|Kotlin}}==
{{trans|Go}}
<langsyntaxhighlight lang="scala">fun lcs(a: List<String>): String {
val le = a.size
if (le == 0) {
Line 1,863 ⟶ 1,937:
println("$test -> `${lcs(test)}`")
}
}</langsyntaxhighlight>
{{out}}
<pre>[baabababc, baabc, bbbabc] -> `abc`
Line 1,873 ⟶ 1,947:
 
=={{header|Ksh}}==
<langsyntaxhighlight lang="ksh">#!/bin/ksh
 
# Longest common suffix
Line 1,920 ⟶ 1,994:
done
echo
</langsyntaxhighlight>{{out}}
<pre>
( Sunday Monday Tuesday Wednesday Thursday Friday Saturday ) -> 'day'
Line 1,931 ⟶ 2,005:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">ClearAll[LCS]
LCS[x_List] := Module[{l, s},
If[Length[x] > 0,
Line 1,951 ⟶ 2,025:
LCS[{""}]
LCS[{}]
LCS[{"ectoplasm", "banana"}]</langsyntaxhighlight>
{{out}}
<pre>"one"
Line 1,964 ⟶ 2,038:
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import sequtils, strformat, strutils
 
func lcs(list: varargs[string]): string =
Line 1,989 ⟶ 2,063:
test()
test("prefix", "suffix")
test("send", "lend")</langsyntaxhighlight>
 
{{out}}
Line 2,003 ⟶ 2,077:
=={{header|Perl}}==
Based on [[Longest_common_prefix]] Perl entry.
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
Line 2,021 ⟶ 2,095:
[ '' ]) {
say qq{'@$words' ==> '@{[lcs(@$words)]}';
}</langsyntaxhighlight>
 
{{out}}
Line 2,034 ⟶ 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:
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
Line 2,066 ⟶ 2,140:
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,080 ⟶ 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 2,129 ⟶ 2,203:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>day
Line 2,138 ⟶ 2,212:
<code>commonprefix</code> is defined at [[Longest common prefix#Quackery]].
 
<langsyntaxhighlight Quackerylang="quackery"> [ [] swap
witheach
[ reverse nested join ]
Line 2,145 ⟶ 2,219:
 
$ "monday tuesday wednesday thursday friday saturday sunday"
nest$ commonsuffix echo$</langsyntaxhighlight>
 
{{out}}
Line 2,154 ⟶ 2,228:
{{works with|Rakudo|2020.07}}
 
<syntaxhighlight lang="raku" perl6line>sub longest-common-suffix ( *@words ) {
return '' unless +@words;
my $min = @words».chars.min;
Line 2,171 ⟶ 2,245:
('one, Hey!', 'three, Hey!', 'ale, Hey!', 'me, Hey!'),
'suffix',
''</langsyntaxhighlight>
{{out}}
<pre>("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday") - LCS: >day<
Line 2,183 ⟶ 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 2,201 ⟶ 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 2,210 ⟶ 2,284:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
 
Line 2,257 ⟶ 2,331:
next
return cStr2
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,265 ⟶ 2,339:
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>
 
=={{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}}==
<langsyntaxhighlight lang="sml">val lcs =
let
val commonSuffix = fn (s0, s1) =>
Line 2,285 ⟶ 2,396:
in
fn [] => "" | x :: xs => foldl commonSuffix x xs
end</langsyntaxhighlight>
 
=={{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 2,312 ⟶ 2,478:
[""]
]
for (test in tests) System.print("%(test) -> \"%(lcs.call(test))\"")</langsyntaxhighlight>
 
{{out}}
Line 2,322 ⟶ 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