Longest common prefix: Difference between revisions

added Easylang
No edit summary
(added Easylang)
 
(8 intermediate revisions by 7 users not shown)
Line 27:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">F lcp(sa)
I sa.empty
R ‘’
Line 53:
test([‘’])
test([‘prefix’, ‘suffix’])
test([‘foo’, ‘foobar’])</langsyntaxhighlight>
 
{{out}}
Line 68:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">DEFINE PTR="CARD"
 
BYTE Func Equals(CHAR ARRAY a,b)
Line 179:
texts(0)=t10 texts(1)=t11
Test(texts,2)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Longest_common_prefix.png Screenshot from Atari 8-bit computer]
Line 194:
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
with Ada.Strings.Unbounded;
 
Line 264:
Ada.Text_IO.Put_Line (Prefix);
 
end Longest_Prefix;</langsyntaxhighlight>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">lcp(...)
{
integer n;
Line 296:
 
0;
}</langsyntaxhighlight>
{{Out}}
<pre>"inters"
Line 310:
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<langsyntaxhighlight lang="algol68"># find the longest common prefix of two strings #
PRIO COMMONPREFIX = 1;
OP COMMONPREFIX = ( STRING a, b )STRING:
Line 380:
test prefix( ( "prefix", "suffix" ), "" );
test prefix( ( "foo", "foobar" ), "foo" )
END</langsyntaxhighlight>
{{out}}
<pre>
Line 396:
=={{header|AppleScript}}==
===AppleScriptObjC===
<langsyntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
 
Line 427:
longestCommonPrefix({}) --> ""
longestCommonPrefix({"prefix", "suffix"}) --> ""
longestCommonPrefix({"foo", "foobar"}) --> "foo"</langsyntaxhighlight>
----
===Functional===
and for more productivity, and higher re-use of existing library functions, we can write a functional definition (rather than a procedure).
 
<langsyntaxhighlight lang="applescript">------------------- LONGEST COMMON PREFIX ------------------
 
 
Line 776:
set my text item delimiters to dlm
str
end unlines</langsyntaxhighlight>
{{Out}}
<pre>['interspecies', 'interstellar', 'interstate'] -> 'inters'
Line 789:
 
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">lcp: function [lst][
ret: ""
idx: 0
Line 812:
print lcp [""]
print lcp ["prefix" "suffix"]
print lcp ["foo" "foobar"]</langsyntaxhighlight>
 
{{out}}
Line 826:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">lcp(data){
for num, v in StrSplit(data.1)
for i, word in data
Line 832:
return SubStr(word, 1, num-1)
return SubStr(word, 1, num)
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % ""
. "`n" lcp(["interspecies","interstellar","interstate"])
. "`n" lcp(["throne","throne"])
Line 843:
. "`n" lcp(["prefix","suffix"])
. "`n" lcp(["foo","foobar"])
return</langsyntaxhighlight>
{{out}}
<pre>
Line 857:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f LONGEST_COMMON_PREFIX.AWK
BEGIN {
Line 904:
return(substr(str,1,lcp_leng))
}
</syntaxhighlight>
</lang>
<p>Output:</p>
<pre>
Line 918:
 
=={{header|C}}==
<syntaxhighlight lang="c">
<lang C>
#include<stdarg.h>
#include<string.h>
Line 980:
return 0;
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 996:
=={{header|C sharp|C#}}==
{{trans|Java}}
<langsyntaxhighlight lang="csharp">using System;
 
namespace LCP {
Line 1,039:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>inters
Line 1,052:
 
=={{header|C++}}==
<langsyntaxhighlight Cpplang="cpp">#include <set>
#include <algorithm>
#include <string>
Line 1,129:
std::cout << "lcp( \"foo\" , \"foobar\" ) = " << lcp ( input ) << std::endl ;
return 0 ;
}</langsyntaxhighlight>
 
Another more concise version (C++14 for comparing dissimilar containers):
 
<langsyntaxhighlight lang="cpp">
#include <algorithm>
#include <string>
Line 1,171:
return 0 ;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,183:
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">lcp = proc (strs: ss) returns (string)
ss = sequence[string]
if ss$empty(strs) then return("") end
Line 1,225:
stream$putl(po, "\"" || lcp(test) || "\"")
end
end start_up</langsyntaxhighlight>
{{out}}
<pre>"inters"
Line 1,239:
=={{header|D}}==
{{trans|Java}}
<langsyntaxhighlight Dlang="d">import std.stdio;
 
string lcp(string[] list ...) {
Line 1,272:
writeln(lcp("prefix","suffix"));
writeln(lcp("foo","foobar"));
}</langsyntaxhighlight>
{{out}}
<pre>inters
Line 1,287:
{{trans|C#}}
 
<langsyntaxhighlight lang="dyalect">func lcp(sa...) {
if sa.Length() == 0 || !sa[0] {
return ""
Line 1,322:
print(lcp(nil))
print(lcp("prefix", "suffix"))
print(lcp("foo", "foobar"))</langsyntaxhighlight>
 
{{out}}
Line 1,335:
 
foo</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight>
func$ lcp list$[] .
if len list$[] = 0
return ""
.
shortest$ = list$[1]
for s$ in list$[]
if len s$ < len shortest$
shortest$ = s$
.
.
for i to len shortest$ - 1
sub$ = substr shortest$ 1 i
for s$ in list$[]
if substr s$ 1 i <> sub$
return substr shortest$ 1 (i - 1)
.
.
.
return shortest$
.
print lcp [ "interspecies" "interstellar" "interstate" ]
print lcp [ "throne" "throne" ]
print lcp [ "throne" "dungeon" ]
print lcp [ "throne" "" "throne" ]
print lcp [ "cheese" ]
print lcp [ ]
print lcp [ "foo" "foobar" ]
</syntaxhighlight>
{{out}}
<pre>
inters
throne
 
 
cheese
 
foo
</pre>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="lisp">
;; find common prefix of two strings
(define (prefix s t ) (for/string ((u s) (v t)) #:break (not (= u v)) u))
Line 1,368 ⟶ 1,409:
("prefix" "suffix") → ""
 
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">
defmodule LCP do
@data [
Line 1,399 ⟶ 1,440:
defp lcp( _, _, pre), do: String.reverse(pre)
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,415 ⟶ 1,456:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
-module(lcp).
-export([ main/0 ]).
Line 1,438 ⟶ 1,479:
lcp([X|Xs], [X|Ys], Pre) -> lcp(Xs, Ys, [X|Pre]);
lcp( _, _, Pre) -> lists:reverse(Pre).
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,454 ⟶ 1,495:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: continuations formatting fry kernel sequences strings ;
IN: rosetta-code.lcp
 
Line 1,480 ⟶ 1,521:
} [ dup lcp "%u lcp = %u\n" printf ] each ;
 
MAIN: lcp-demo</langsyntaxhighlight>
{{out}}
<pre>
Line 1,495 ⟶ 1,536:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function lcp(s() As String) As String
Line 1,556 ⟶ 1,597:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,572 ⟶ 1,613:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,625 ⟶ 1,666:
fmt.Printf("lcp(%q) = %q\n", l, lcp(l))
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,641 ⟶ 1,682:
=={{header|Haskell}}==
This even works on infinite strings (that have a finite longest common prefix), due to Haskell's laziness.
<langsyntaxhighlight lang="haskell">import Data.List (intercalate, transpose)
 
lcp :: (Eq a) => [[a]] -> [a]
Line 1,664 ⟶ 1,705:
 
showPrefix :: [String] -> String
showPrefix = ((<>) . (<> " -> ") . show) <*> (show . lcp)</langsyntaxhighlight>
{{Out}}
<pre>["interspecies","interstellar","interstate"] -> "inters"
Line 1,678 ⟶ 1,719:
=={{header|J}}==
 
<langsyntaxhighlight Jlang="j">lcp=: {. {.~ 0 i.~ [: */2 =/\ ]</langsyntaxhighlight>
 
In other words: compare adjacent strings pair-wise, combine results logically, find first mismatch in any of them, take that many characters from the first of the strings.
Line 1,688 ⟶ 1,729:
Examples:
 
<langsyntaxhighlight Jlang="j"> lcp 'interspecies','interstellar',:'interstate'
inters
lcp 'throne',:'throne'
Line 1,701 ⟶ 1,742:
 
lcp 'prefix',:'suffix'
</syntaxhighlight>
</lang>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">public class LCP {
public static String lcp(String... list){
if(list == null) return "";//special case
Line 1,740 ⟶ 1,781:
System.out.println(lcp("foo","foobar"));
}
}</langsyntaxhighlight>
{{out}}
<pre>inters
Line 1,756 ⟶ 1,797:
===ES5===
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
'use strict';
 
Line 1,817 ⟶ 1,858:
];
 
})();</langsyntaxhighlight>
 
{{Out}}
 
<langsyntaxhighlight JavaScriptlang="javascript">[true, true, true, true, true, true, true]</langsyntaxhighlight>
 
 
Line 1,832 ⟶ 1,873:
This functionally implemented zip is significantly slower than the iterative version used above:
 
<langsyntaxhighlight JavaScriptlang="javascript">// Zip arbitrary number of lists (a functional implementation, this time)
// Accepts arrays or strings, and returns [[a]]
function zip() {
Line 1,852 ⟶ 1,893:
}, null)
} else return [];
}</langsyntaxhighlight>
 
===ES6===
<langsyntaxhighlight lang="javascript">(() => {
"use strict";
 
Line 1,948 ⟶ 1,989:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>["interspecies","interstellar","interstate"] -> "inters"
Line 1,963 ⟶ 2,004:
 
See [[#Scala]] for a description of the approach used in this section.
<langsyntaxhighlight lang="jq"># If your jq includes until/2
# then feel free to omit the following definition:
def until(cond; next):
def _until: if cond then . else (next|_until) end; _until;</langsyntaxhighlight>
 
<langsyntaxhighlight lang="jq">def longest_common_prefix:
if length == 0 then "" # by convention
elif length == 1 then .[0] # for speed
Line 1,979 ⟶ 2,020:
| $first[0:.]
end
end;</langsyntaxhighlight>
 
'''Test Cases'''
<langsyntaxhighlight lang="jq">def check(ans): longest_common_prefix == ans;
 
(["interspecies","interstellar","interstate"] | check("inters")) and
Line 1,993 ⟶ 2,034:
(["prefix","suffix"] | check("")) and
(["foo","foobar"] | check("foo"))
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -n -f longest_common_prefix.jq
true</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">function lcp(str::AbstractString...)
r = IOBuffer()
str = [str...]
Line 2,022 ⟶ 2,063:
@show lcp()
@show lcp("prefix","suffix")
@show lcp("foo","foobar")</langsyntaxhighlight>
 
{{out}}
Line 2,036 ⟶ 2,077:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun lcp(vararg sa: String): String {
Line 2,064 ⟶ 2,105:
println("""["prefix","suffix"] = "${lcp("prefix", "suffix")}"""")
println("""["foo","foobar"] = "${lcp("foo", "foobar")}"""")
}</langsyntaxhighlight>
 
{{out}}
Line 2,083 ⟶ 2,124:
=={{header|Lobster}}==
{{trans|Go}}
<langsyntaxhighlight Lobsterlang="lobster">// lcp finds the longest common prefix of the input strings
 
def lcp(l):
Line 2,119 ⟶ 2,160:
["prefix", "suffix"],
["foo", "foobar"]]):
print("lcp" + _ + " = \"" + lcp(_) + "\"")</langsyntaxhighlight>
{{out}}
<pre>lcp["interspecies", "interstellar", "interstate"] = "inters"
Line 2,133 ⟶ 2,174:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">function lcp (strList)
local shortest, prefix, first = math.huge, ""
for _, str in pairs(strList) do
Line 2,168 ⟶ 2,209:
pre = lcp(stringList)
if pre == "" then print(string.char(238)) else print(pre) end
end</langsyntaxhighlight>
{{out}}
<pre>inters
Line 2,181 ⟶ 2,222:
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">lcp := proc(arr)
local A:
if (arr = []) then return "": end if:
A := sort(arr):
return (A[1][1..(StringTools:-CommonPrefix(A[1],A[-1]))]):
end proc:</langsyntaxhighlight>
'''Test Cases'''
<langsyntaxhighlight Maplelang="maple">lcp(["interspecies","interstellar","interstate"]);
lcp(["throne","throne"]);
lcp(["throne","dungeon"]);
Line 2,196 ⟶ 2,237:
lcp([]);
lcp(["prefix","suffix"]);
lcp(["foo","foobar"]);</langsyntaxhighlight>
{{out}}
<pre>inters
Line 2,209 ⟶ 2,250:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">ClearAll[LCP]
LCP[x_List] := Module[{l, s},
If[Length[x] > 0,
Line 2,229 ⟶ 2,270:
LCP[{}]
LCP[{"prefix", "suffix"}]
LCP[{"foo", "foobar"}]</langsyntaxhighlight>
{{out}}
<pre>"inters"
Line 2,242 ⟶ 2,283:
 
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang="matlab">
<lang Matlab>
function lcp = longest_common_prefix(varargin)
ca = char(varargin);
Line 2,250 ⟶ 2,291:
 
longest_common_prefix('aa', 'aa', 'aac')
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,259 ⟶ 2,300:
=={{header|MiniScript}}==
We find the shortest and longest strings (without sorting, which makes the code slightly longer but much more efficient), and then just compare those.
<langsyntaxhighlight MiniScriptlang="miniscript">lcp = function(strList)
if not strList then return null
// find the shortest and longest strings (without sorting!)
Line 2,282 ⟶ 2,323:
print lcp(["cheese"])
print lcp([])
print lcp(["foo","foobar"])</langsyntaxhighlight>
 
{{out}}
Line 2,292 ⟶ 2,333:
null
foo</pre>
 
=={{header|Miranda}}==
<syntaxhighlight lang="miranda">main :: [sys_message]
main = [Stdout (lay (map test tests))]
 
test :: [[char]]->[char]
test strings = show strings ++ " = " ++ show (lcp strings)
 
tests :: [[[char]]]
tests = [["interspecies","interstellar","interstate"],
["throne","throne"],
["throne","dungeon"],
["throne","","throne"],
[""],
[],
["prefix","suffix"],
["foo","foobar"]]
 
lcp :: [[char]]->[char]
lcp strings = map hd (takewhile same (transpose truncated))
where same (a:as) = and [c=a | c<-as]
truncated = map (take length) strings
length = min (map (#) strings)</syntaxhighlight>
{{out}}
<pre>main :: [sys_message]
main = [Stdout (lay (map test tests))]
 
test :: [[char]]->[char]
test strings = show strings ++ " = " ++ show (lcp strings)
 
tests :: [[[char]]]
tests = [["interspecies","interstellar","interstate"],
["throne","throne"],
["throne","dungeon"],
["throne","","throne"],
[""],
[],
["prefix","suffix"],
["foo","foobar"]]
 
lcp :: [[char]]->[char]
lcp strings = map hd (takewhile same (transpose truncated))
where same (a:as) = and [c=a | c<-as]
truncated = map (take length) strings
length = min (map (#) strings)</pre>
 
=={{header|Modula-2}}==
{{trans|C#}}
<langsyntaxhighlight lang="modula2">MODULE LCP;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
 
Line 2,366 ⟶ 2,452:
 
ReadChar
END LCP.</langsyntaxhighlight>
{{out}}
<pre>inters
Line 2,377 ⟶ 2,463:
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import sequtils, strformat, strutils
 
func lcp(list: varargs[string]): string =
Line 2,402 ⟶ 2,488:
test()
test("prefix", "suffix")
test("foo", "foobar")</langsyntaxhighlight>
 
{{out}}
Line 2,415 ⟶ 2,501:
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
(define (lcp . args)
(if (null? args)
Line 2,434 ⟶ 2,520:
(print "> " (lcp "prefix" "suffix"))
(print "> " (lcp "foo" "foobar"))
</syntaxhighlight>
</lang>
{Out}
<pre>
Line 2,450 ⟶ 2,536:
==ooRexx==
{{trans|REXX}}
<langsyntaxhighlight lang="oorexx">Call assert lcp(.list~of("interspecies","interstellar","interstate")),"inters"
Call assert lcp(.list~of("throne","throne")),"throne"
Call assert lcp(.list~of("throne","dungeon")),""
Line 2,485 ⟶ 2,571:
Leave
End
Return left(arg(1),i-1)</langsyntaxhighlight>
{{out}}
<pre>lcp(interspecies,interstellar,interstate)
Line 2,512 ⟶ 2,598:
If the strings are known not to contain null-bytes, we can let the regex backtracking engine find the longest common prefix like this:
 
<langsyntaxhighlight lang="perl">sub lcp {
(join("\0", @_) =~ /^ ([^\0]*) [^\0]* (?:\0 \1 [^\0]*)* $/sx)[0];
}</langsyntaxhighlight>
 
Testing:
<langsyntaxhighlight lang="perl">use Test::More;
plan tests => 8;
 
Line 2,527 ⟶ 2,613:
is lcp(), "";
is lcp("prefix","suffix"), "";
is lcp("foo","foobar"), "foo";</langsyntaxhighlight>
 
{{out}}
Line 2,533 ⟶ 2,619:
 
=={{header|Phix}}==
<!--<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;">lcp</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,566 ⟶ 2,652:
<span style="color: #0000FF;">?</span><span style="color: #000000;">lcp</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,582 ⟶ 2,668:
=={{header|PL/I}}==
{{trans|REXX}}
<langsyntaxhighlight lang="pli">*process source xref attributes or(!);
(subrg):
lcpt: Proc Options(main);
Line 2,634 ⟶ 2,720:
End;
 
End;</langsyntaxhighlight>
{{out}}
<pre>"interspecies interstellar interstate"
Line 2,658 ⟶ 2,744:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function lcp ($arr) {
if($arr){
Line 2,686 ⟶ 2,772:
show @("prefix","suffix")
show @("foo","foobar")
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 2,702 ⟶ 2,788:
=={{header|Prolog}}==
{{works with|SWI Prolog}}
<langsyntaxhighlight lang="prolog">common_prefix(String1, String2, Prefix):-
string_chars(String1, Chars1),
string_chars(String2, Chars2),
Line 2,736 ⟶ 2,822:
test([]),
test(["prefix", "suffix"]),
test(["foo", "foobar"]).</langsyntaxhighlight>
 
{{out}}
Line 2,754 ⟶ 2,840:
Note: this makes use of the error in <code>os.path.commonprefix</code> where it computes the longest common prefix regardless of directory separators rather than [[Find common directory path#Python|finding the common directory path]].
 
<langsyntaxhighlight lang="python">import os.path
 
def lcp(*s):
Line 2,765 ⟶ 2,851:
assert lcp("") == ""
assert lcp("prefix","suffix") == ""
assert lcp("foo","foobar") == "foo"</langsyntaxhighlight>
 
===Python: Functional===
To see if all the n'th characters are the same I compare the min and max characters in the lambda function.
 
<langsyntaxhighlight lang="python">from itertools import takewhile
 
def lcp(*s):
Line 2,782 ⟶ 2,868:
assert lcp("") == ""
assert lcp("prefix","suffix") == ""
assert lcp("foo","foobar") == "foo"</langsyntaxhighlight>
 
The above runs without output.
Line 2,788 ⟶ 2,874:
;Alternative Functional:
An alternative solution that takes advantage of the observation that the longest common prefix of a set of strings must be the same as the longest common prefix of the lexicographically minimal string and the lexicographically maximal string, since moving away lexicographically can only shorten the common prefix, never lengthening it. Finding the min and max could do a lot of unnecessary work though, if the strings are long and the common prefix is short.
<langsyntaxhighlight lang="python">from itertools import takewhile
 
def lcp(*s):
return ''.join(a for a,b in takewhile(lambda x: x[0] == x[1],
zip(min(s), max(s))))</langsyntaxhighlight>
 
 
Or, defined in terms of a generic '''transpose''' function:
<langsyntaxhighlight Pythonlang="python">from itertools import (takewhile)
 
 
Line 2,845 ⟶ 2,931:
# TEST ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>[interspecies, interstellar, interstate] -> inters
Line 2,857 ⟶ 2,943:
=={{header|Quackery}}==
 
<syntaxhighlight lang="text"> [ dup [] = iff
[ drop true ] done
true swap
Line 2,918 ⟶ 3,004:
$ "foo foobar"
nest$ commonprefix echoresult</langsyntaxhighlight>
 
{{out}}
Line 2,937 ⟶ 3,023:
Note that there are three cases to the match, because <code>zip</code> needs at least one list, and <code>char=?</code> needs at least 2 characters to compare.
 
<syntaxhighlight lang="text">#lang racket
(require srfi/1)
 
Line 2,960 ⟶ 3,046:
(lcp ε) => ε
(lcp) => ε
(lcp "prefix" "suffix") => ε))</langsyntaxhighlight>
 
All tests pass.
Line 2,968 ⟶ 3,054:
{{works with|rakudo|2015-11-28}}
This should work on infinite strings (if and when we get them), since <tt>.ords</tt> is lazy. In any case, it does just about the minimal work by evaluating all strings lazily in parallel. A few explanations of the juicy bits: <tt>@s</tt> is the list of strings, and the hyper operator <tt>»</tt> applies the <tt>.ords</tt> to each of those strings, producing a list of lists. The <tt>|</tt> operator inserts each of those sublists as an argument into an argument list so that we can use a reduction operator across the list of lists, which makes sense if the operator in question knows how to deal with list arguments. In this case we use the <tt>Z</tt> ('zip') metaoperator with <tt>eqv</tt> as a base operator, which runs <tt>eqv</tt> across all the lists in parallel for each position, and will fail if not all the lists have the same ordinal value at that position, or if any of the strings run out of characters. Then we count up the leading matching positions and carve up one of the strings to that length.
<syntaxhighlight lang="raku" perl6line>multi lcp() { '' }
multi lcp($s) { ~$s }
multi lcp(*@s) { substr @s[0], 0, [+] [\and] [Zeqv] |@s».ords }
Line 2,982 ⟶ 3,068:
is lcp(), '';
is lcp("prefix","suffix"), '';
is lcp("foo","foobar"), 'foo';</langsyntaxhighlight>
{{out}}
<pre>1..8
Line 2,996 ⟶ 3,082:
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/* REXX */
Call assert lcp("interspecies","interstellar","interstate"),"inters"
Call assert lcp("throne","throne"),"throne"
Line 3,036 ⟶ 3,122:
Leave
End
Return left(arg(1),i-1)</langsyntaxhighlight>
{{out}}
<pre>test lcp("interspecies","interstellar","interstate")
Line 3,067 ⟶ 3,153:
===version 2===
This REXX version makes use of the &nbsp; '''compare''' &nbsp; BIF.
<langsyntaxhighlight lang="rexx">/*REXX program computes the longest common prefix (LCP) of any number of strings.*/
say LCP('interspecies', "interstellar", 'interstate')
say LCP('throne', "throne") /*2 strings, they are exactly the same.*/
Line 3,089 ⟶ 3,175:
m= t - 1; @= left(@, max(0, m) ) /*define maximum. */
end /*j*/
return ' longest common prefix=' @ /*return answer. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 3,136 ⟶ 3,222:
===version 3===
This REXX version explicitly shows &nbsp; ''null'' &nbsp; values and the number of strings specified.
<langsyntaxhighlight lang="rexx">/*REXX program computes the longest common prefix (LCP) of any number of strings.*/
say LCP('interspecies', "interstellar", 'interstate')
say LCP('throne', "throne") /*2 strings, they are exactly the same.*/
Line 3,162 ⟶ 3,248:
return ' longest common prefix=' shownull(@) /*return answer. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
showNull: procedure; parse arg z; if z=='' then z= "«null»"; return z</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 3,218 ⟶ 3,304:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Longest common prefix
 
Line 3,249 ⟶ 3,335:
see comp + nl
ok
</syntaxhighlight>
</lang>
Output:
<pre>
inters
</pre>
 
=={{header|RPL}}==
≪ DUP SIZE → n
≪ '''CASE'''
n NOT '''THEN''' DROP "" '''END'''
n 1 == '''THEN''' 1 GET '''END'''
DUP ≪ SIZE ≫ DOLIST ≪ MIN ≫ STREAM <span style="color:grey">@ get the size of the smallest string</span>
'''IF''' DUP NOT '''THEN''' DROP2 "" '''ELSE'''
1 OVER '''FOR''' j
OVER 1 ≪ 1 j SUB ≫ DOLIST
'''IF''' ≪ == ≫ DOSUBS 1 + ΠLIST NOT '''THEN'''
j 1 - SWAP ‘j’ STO '''END'''
'''NEXT'''
SWAP 1 GET 1 ROT SUB
'''END END'''
≫ ≫ '<span style="color:blue">LCP</span>' STO
 
{ { "interspecies" "interstellar" "interstate" } { "throne" "throne" } { "throne" "dungeon" }{ "throne" "" "throne" } { "cheese" } { "" } { } { "prefix" "suffix" } { "foo" "foobar" } } ≪ <span style="color:blue">LCP</span> ≫ DOLIST
{{out}}
<pre>
1: { "inters" "throne" "" "" "cheese" "" "" "" "foo" }
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def lcp(*strs)
return "" if strs.empty?
min, max = strs.minmax
Line 3,277 ⟶ 3,385:
data.each do |set|
puts "lcp(#{set.inspect[1..-2]}) = #{lcp(*set).inspect}"
end</langsyntaxhighlight>
 
{{out}}
Line 3,296 ⟶ 3,404:
Rust String by default is utf-8 encoded. Since utf-8 is variable width, indexing in constant time is not possible. This example therefore uses byte strings (slices of u8) for the strings. The implementation shown here is similar to the Java implementation.
 
<syntaxhighlight lang="rust">
<lang Rust>
fn main() {
let strs: [&[&[u8]]; 7] = [
Line 3,339 ⟶ 3,447:
}
}
</syntaxhighlight>
</lang>
 
'''Output:'''
Line 3,358 ⟶ 3,466:
> zip takeWhile: (i,i), (n,n), (t,t), (e,e), (r,r), (s,s) unzip < > "inters"
"intesteller" / \ i, n, t, e, r, s
</pre><langsyntaxhighlight lang="scala">class TestLCP extends FunSuite {
test("shared start") {
assert(lcp("interspecies","interstellar","interstate") === "inters")
Line 3,371 ⟶ 3,479:
def lcp(list: String*) = list.foldLeft("")((_,_) =>
(list.min.view,list.max.view).zipped.takeWhile(v => v._1 == v._2).unzip._1.mkString)
}</langsyntaxhighlight>
 
=={{header|sed}}==
<syntaxhighlight lang="sed">$q
N
s/^\(.*\).*\(\n\)\1.*/\2\1/
D</syntaxhighlight>
{{out}}
<pre>
$ printf '%s\n' interspecies interstellar interstate | sed -f lcp.sed
inters
$ printf '%s\n' throne throne | sed -f lcp.sed
throne
$ printf '%s\n' throne dungeon | sed -f lcp.sed
 
$ printf '%s\n' throne '' throne | sed -f lcp.sed
 
$ printf '%s\n' cheese | sed -f lcp.sed
cheese
$ printf '%s\n' '' | sed -f lcp.sed
 
$ printf '%s\n' prefix suffix | sed -f lcp.sed
 
$ printf '%s\n' foo foobar | sed -f lcp.sed
foo
</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby"># Finds the first point where the tree bifurcates
func find_common_prefix(hash, acc) {
if (hash.len == 1) {
Line 3,402 ⟶ 3,535:
 
return find_common_prefix(hash, '')
}</langsyntaxhighlight>
 
Demonstration:
<langsyntaxhighlight lang="ruby">var data = [
["interspecies","interstellar","interstate"],
["throne","throne"],
Line 3,419 ⟶ 3,552:
data.each { |set|
say "lcp(#{set.dump.substr(1,-1)}) = #{lcp(set...).dump}";
};</langsyntaxhighlight>
{{out}}
<pre>
Line 3,436 ⟶ 3,569:
{{works with|Smalltalk/X}}
There is already a longestCommonPrefix method in Collection; however, if there wasn't, the following will do:
<langsyntaxhighlight lang="smalltalk">prefixLength := [:a :b |
|end|
end := (a size) min:(b size).
Line 3,464 ⟶ 3,597:
) do:[:eachList |
Transcript show:eachList storeString; show:' ==> '; showCR:(lcp value:eachList)
]</langsyntaxhighlight>
{{out}}
<pre>#('interspecies' 'interstellar' 'interstate') ==> inters
Line 3,477 ⟶ 3,610:
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">val lcp =
let
val longerFirst = fn pair as (a, b) =>
Line 3,487 ⟶ 3,620:
in
fn [] => "" | x :: xs => foldl (commonPrefix o longerFirst) x xs
end</langsyntaxhighlight>
;Test<nowiki>:</nowiki>
<langsyntaxhighlight lang="sml">val test = [
["interspecies", "interstellar", "interstate"],
["throne", "throne"],
Line 3,501 ⟶ 3,634:
]
 
val () = (print o concat o map (fn lst => "'" ^ lcp lst ^ "'\n")) test</langsyntaxhighlight>
{{out}}
<pre>'inters'
Line 3,514 ⟶ 3,647:
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">func commonPrefix(string1: String, string2: String) -> String {
return String(zip(string1, string2).prefix(while: {$0 == $1}).map{$0.0})
}
Line 3,541 ⟶ 3,674:
printLongestCommonPrefix([])
printLongestCommonPrefix(["prefix", "suffix"])
printLongestCommonPrefix(["foo", "foobar"])</langsyntaxhighlight>
 
{{out}}
Line 3,560 ⟶ 3,693:
Since [http://www.tcl.tk/cgi-bin/tct/tip/195.html TIP#195] this has been present as a core command:
 
<langsyntaxhighlight Tcllang="tcl">% namespace import ::tcl::prefix
% prefix longest {interstellar interspecies interstate integer} ""
inte
</syntaxhighlight>
</lang>
 
=={{header|UNIX Shell}}==
{{works with|bash}}
 
<langsyntaxhighlight lang="bash">#!/bin/bash
 
lcp () {
Line 3,613 ⟶ 3,746:
printf '%s -> "%s"\n' "$(declare -p words)" "$(lcp "${words[@]}")"
done
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,627 ⟶ 3,760:
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">Function lcp(s)
'declare an array
str = Split(s,",")
Line 3,679 ⟶ 3,812:
WScript.StdOut.Write "Test case " & n & " " & test(n) & " = " & lcp(test(n))
WScript.StdOut.WriteLine
Next</langsyntaxhighlight>
 
{{out}}
Line 3,691 ⟶ 3,824:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Module Module1
 
Function LongestCommonPrefix(ParamArray sa() As String) As String
Line 3,736 ⟶ 3,869:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>inters
Line 3,748 ⟶ 3,881:
foo</pre>
 
=={{header|V (Vlang)}}==
{{trans|go}}
<syntaxhighlight lang="v (vlang)">// lcp finds the longest common prefix of the input strings.
// It compares by bytes instead of runes (Unicode code points).
// It's up to the caller to do Unicode normalization if desired
// (e.g. see golang.org/x/text/unicode/norm).
fn lcp(l []string) string {
// Special cases first
Line 3,801 ⟶ 3,931:
println("lcp($l) = ${lcp(l)}")
}
}</langsyntaxhighlight>
{{out}}
<pre>Same as Go entry</pre>
Line 3,808 ⟶ 3,938:
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
 
var lcp = Fn.new { |sa|
Line 3,839 ⟶ 3,969:
for (sa in lists) {
Fmt.print(" $-46s = $q", Fmt.v("q", 0, sa), lcp.call(sa))
}</langsyntaxhighlight>
 
{{out}}
Line 3,857 ⟶ 3,987:
 
=={{header|XProfan}}==
<langsyntaxhighlight XProfanlang="xprofan">Proc lcp
Parameters long liste
Declare int longest, j, L, string s,t
Line 3,903 ⟶ 4,033:
ClearList 0
WaitKey
end</langsyntaxhighlight>
{{out}}
<pre>
Line 3,918 ⟶ 4,048:
=={{header|zkl}}==
The string method prefix returns the number of common prefix characters.
<langsyntaxhighlight lang="zkl">fcn lcp(s,strings){ s[0,s.prefix(vm.pasteArgs(1))] }</langsyntaxhighlight>
Or, without using prefix:
{{trans|Scala}}
<langsyntaxhighlight lang="zkl">fcn lcp(strings){
vm.arglist.reduce(fcn(prefix,s){ Utils.Helpers.zipW(prefix,s) // lazy zip
.pump(String,fcn([(a,b)]){ a==b and a or Void.Stop })
})
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">tester:=TheVault.Test.UnitTester.UnitTester();
tester.testRun(lcp.fp("interspecies","interstellar","interstate"),Void,"inters",__LINE__);
tester.testRun(lcp.fp("throne","throne"),Void,"throne",__LINE__);
Line 3,933 ⟶ 4,063:
tester.testRun(lcp.fp(""),Void,"",__LINE__);
tester.testRun(lcp.fp("prefix","suffix"),Void,"",__LINE__);
tester.stats();</langsyntaxhighlight>
The fp (partial application) method is used to delay running lcp until the tester actually tests.
{{out}}
1,981

edits