Greatest common substring
$begingroup$
Create a program or function which takes a list of strings as input, and outputs the longest string that is a substring of all input strings. If there are several substrings of equal length, and no longer substring, output any one of them.
- This may mean outputting the empty string.
- If there are several valid outputs, you may output any one of them. You are not required to give consistent output for a given input so long as the output is always valid.
- There will always be at least one string in the input, but there might not be a non-empty string.
- All printable ASCII characters may appear in the input. You may assume those are the only characters that appear.
- You may take input or produce output by any of the default methods.
Standard loopholes aren't allowed.- This is code-golf - the fewer bytes of code, the better.
Test cases:
[Inputs] -> [Valid outputs (choose one)]
["hello", "'ello"] -> ["ello"]
["very", "much", "different"] -> [""]
["empty", "", "STRING"] -> [""]
["identical", "identical"] -> ["identical"]
["string", "stRIng"] -> ["st", "ng"]
["this one", "is a substring of this one"] -> ["this one"]
["just one"] -> ["just one"]
["", "", ""] -> [""]
["many outputs", "stuptuo ynam"] -> ["m", "a", "n", "y", " ", "o", "u", "t", "p", "s"]
["many inputs", "any inputs", "ny iii", "yanny"] -> ["ny"]
["%%not&", "ju&#st", "[&]alpha_numeric"] -> ["&"]
code-golf string subsequence
$endgroup$
|
show 4 more comments
$begingroup$
Create a program or function which takes a list of strings as input, and outputs the longest string that is a substring of all input strings. If there are several substrings of equal length, and no longer substring, output any one of them.
- This may mean outputting the empty string.
- If there are several valid outputs, you may output any one of them. You are not required to give consistent output for a given input so long as the output is always valid.
- There will always be at least one string in the input, but there might not be a non-empty string.
- All printable ASCII characters may appear in the input. You may assume those are the only characters that appear.
- You may take input or produce output by any of the default methods.
Standard loopholes aren't allowed.- This is code-golf - the fewer bytes of code, the better.
Test cases:
[Inputs] -> [Valid outputs (choose one)]
["hello", "'ello"] -> ["ello"]
["very", "much", "different"] -> [""]
["empty", "", "STRING"] -> [""]
["identical", "identical"] -> ["identical"]
["string", "stRIng"] -> ["st", "ng"]
["this one", "is a substring of this one"] -> ["this one"]
["just one"] -> ["just one"]
["", "", ""] -> [""]
["many outputs", "stuptuo ynam"] -> ["m", "a", "n", "y", " ", "o", "u", "t", "p", "s"]
["many inputs", "any inputs", "ny iii", "yanny"] -> ["ny"]
["%%not&", "ju&#st", "[&]alpha_numeric"] -> ["&"]
code-golf string subsequence
$endgroup$
$begingroup$
Possible duplicate
$endgroup$
– Adám
Mar 25 at 0:51
2
$begingroup$
@Adám That question asks for the longest common subsequence, not substring.
$endgroup$
– Doorknob♦
Mar 25 at 0:58
1
$begingroup$
Will the strings be only alphanumeric, or alphabetic, or only printable-ascii?
$endgroup$
– Embodiment of Ignorance
Mar 25 at 1:57
$begingroup$
@EmbodimentofIgnorance All printable ASCII characters can appear in the input.
$endgroup$
– Sara J
Mar 25 at 2:11
2
$begingroup$
@Shaggy Generally, no. If the two can be distinguished,undefinedimplies there's no valid output string. If the empty string (or any other string) is a valid output, claiming there is no valid output is incorrect.
$endgroup$
– Sara J
Mar 25 at 10:03
|
show 4 more comments
$begingroup$
Create a program or function which takes a list of strings as input, and outputs the longest string that is a substring of all input strings. If there are several substrings of equal length, and no longer substring, output any one of them.
- This may mean outputting the empty string.
- If there are several valid outputs, you may output any one of them. You are not required to give consistent output for a given input so long as the output is always valid.
- There will always be at least one string in the input, but there might not be a non-empty string.
- All printable ASCII characters may appear in the input. You may assume those are the only characters that appear.
- You may take input or produce output by any of the default methods.
Standard loopholes aren't allowed.- This is code-golf - the fewer bytes of code, the better.
Test cases:
[Inputs] -> [Valid outputs (choose one)]
["hello", "'ello"] -> ["ello"]
["very", "much", "different"] -> [""]
["empty", "", "STRING"] -> [""]
["identical", "identical"] -> ["identical"]
["string", "stRIng"] -> ["st", "ng"]
["this one", "is a substring of this one"] -> ["this one"]
["just one"] -> ["just one"]
["", "", ""] -> [""]
["many outputs", "stuptuo ynam"] -> ["m", "a", "n", "y", " ", "o", "u", "t", "p", "s"]
["many inputs", "any inputs", "ny iii", "yanny"] -> ["ny"]
["%%not&", "ju&#st", "[&]alpha_numeric"] -> ["&"]
code-golf string subsequence
$endgroup$
Create a program or function which takes a list of strings as input, and outputs the longest string that is a substring of all input strings. If there are several substrings of equal length, and no longer substring, output any one of them.
- This may mean outputting the empty string.
- If there are several valid outputs, you may output any one of them. You are not required to give consistent output for a given input so long as the output is always valid.
- There will always be at least one string in the input, but there might not be a non-empty string.
- All printable ASCII characters may appear in the input. You may assume those are the only characters that appear.
- You may take input or produce output by any of the default methods.
Standard loopholes aren't allowed.- This is code-golf - the fewer bytes of code, the better.
Test cases:
[Inputs] -> [Valid outputs (choose one)]
["hello", "'ello"] -> ["ello"]
["very", "much", "different"] -> [""]
["empty", "", "STRING"] -> [""]
["identical", "identical"] -> ["identical"]
["string", "stRIng"] -> ["st", "ng"]
["this one", "is a substring of this one"] -> ["this one"]
["just one"] -> ["just one"]
["", "", ""] -> [""]
["many outputs", "stuptuo ynam"] -> ["m", "a", "n", "y", " ", "o", "u", "t", "p", "s"]
["many inputs", "any inputs", "ny iii", "yanny"] -> ["ny"]
["%%not&", "ju&#st", "[&]alpha_numeric"] -> ["&"]
code-golf string subsequence
code-golf string subsequence
edited Mar 25 at 16:30
Toby Speight
4,48711535
4,48711535
asked Mar 25 at 0:35
Sara JSara J
495210
495210
$begingroup$
Possible duplicate
$endgroup$
– Adám
Mar 25 at 0:51
2
$begingroup$
@Adám That question asks for the longest common subsequence, not substring.
$endgroup$
– Doorknob♦
Mar 25 at 0:58
1
$begingroup$
Will the strings be only alphanumeric, or alphabetic, or only printable-ascii?
$endgroup$
– Embodiment of Ignorance
Mar 25 at 1:57
$begingroup$
@EmbodimentofIgnorance All printable ASCII characters can appear in the input.
$endgroup$
– Sara J
Mar 25 at 2:11
2
$begingroup$
@Shaggy Generally, no. If the two can be distinguished,undefinedimplies there's no valid output string. If the empty string (or any other string) is a valid output, claiming there is no valid output is incorrect.
$endgroup$
– Sara J
Mar 25 at 10:03
|
show 4 more comments
$begingroup$
Possible duplicate
$endgroup$
– Adám
Mar 25 at 0:51
2
$begingroup$
@Adám That question asks for the longest common subsequence, not substring.
$endgroup$
– Doorknob♦
Mar 25 at 0:58
1
$begingroup$
Will the strings be only alphanumeric, or alphabetic, or only printable-ascii?
$endgroup$
– Embodiment of Ignorance
Mar 25 at 1:57
$begingroup$
@EmbodimentofIgnorance All printable ASCII characters can appear in the input.
$endgroup$
– Sara J
Mar 25 at 2:11
2
$begingroup$
@Shaggy Generally, no. If the two can be distinguished,undefinedimplies there's no valid output string. If the empty string (or any other string) is a valid output, claiming there is no valid output is incorrect.
$endgroup$
– Sara J
Mar 25 at 10:03
$begingroup$
Possible duplicate
$endgroup$
– Adám
Mar 25 at 0:51
$begingroup$
Possible duplicate
$endgroup$
– Adám
Mar 25 at 0:51
2
2
$begingroup$
@Adám That question asks for the longest common subsequence, not substring.
$endgroup$
– Doorknob♦
Mar 25 at 0:58
$begingroup$
@Adám That question asks for the longest common subsequence, not substring.
$endgroup$
– Doorknob♦
Mar 25 at 0:58
1
1
$begingroup$
Will the strings be only alphanumeric, or alphabetic, or only printable-ascii?
$endgroup$
– Embodiment of Ignorance
Mar 25 at 1:57
$begingroup$
Will the strings be only alphanumeric, or alphabetic, or only printable-ascii?
$endgroup$
– Embodiment of Ignorance
Mar 25 at 1:57
$begingroup$
@EmbodimentofIgnorance All printable ASCII characters can appear in the input.
$endgroup$
– Sara J
Mar 25 at 2:11
$begingroup$
@EmbodimentofIgnorance All printable ASCII characters can appear in the input.
$endgroup$
– Sara J
Mar 25 at 2:11
2
2
$begingroup$
@Shaggy Generally, no. If the two can be distinguished,
undefined implies there's no valid output string. If the empty string (or any other string) is a valid output, claiming there is no valid output is incorrect.$endgroup$
– Sara J
Mar 25 at 10:03
$begingroup$
@Shaggy Generally, no. If the two can be distinguished,
undefined implies there's no valid output string. If the empty string (or any other string) is a valid output, claiming there is no valid output is incorrect.$endgroup$
– Sara J
Mar 25 at 10:03
|
show 4 more comments
28 Answers
28
active
oldest
votes
$begingroup$
Brachylog (v2), 3 9 bytes
{sᵛ}ᶠlᵒtw
Try it online!
Full program. Input from standard input (as a JSON-style list of strings), output to standard output.
Explanation
{sᵛ}ᶠlᵒtw
s Find a substring
ᵛ of every element {of the input}; the same one for each
{ }ᶠ Convert generator to list
lᵒt Take list element with maximum length
w Output it
Apparently, the tiebreak order on s is not what it is in nearly everything else in Brachylog, so we need to manually override it to produce the longest output. (That's a bit frustrating: four extra characters for the override, plus two grouping characters because Brachylog doesn't parse two metapredicates in a row.)
Brachylog's s doesn't return empty substrings, so we need a bit of a trick to get around that: instead of making a function submission (which is what's normally done), we write a full program, outputting to standard output. That way, if there's a common substring, we just output it, and we're done. If there isn't a common substring, the program errors out – but it still prints nothing to standard output, thus it outputs the null string as intended.
$endgroup$
1
$begingroup$
I tried this with the input ["many inpuabts", "any inabputs", "ny iabii", "yanabny"]. I expected the results ab and ny. But only got the result a. Am I doing something wrong ?
$endgroup$
– t-clausen.dk
Mar 25 at 11:54
$begingroup$
Ugh, seems I remembered the tiebreak order forswrong, and overriding the tiebreak order is rather expensive byte-wise. Doing that now anyway, though, because it's important for the answer to be correct. Somehow none of the test cases I tried noticed the difference.
$endgroup$
– ais523
Mar 25 at 12:21
$begingroup$
@ais523 The ordersproduces substrings is by first giving all prefixes of the input (longest first), then dropping the first one and repeat
$endgroup$
– Kroppeb
Mar 25 at 17:05
add a comment |
$begingroup$
Python 2, 82 bytes
f=lambda h,*t:h and max(h*all(h in s for s in t),f(h[1:],*t),f(h[:-1],*t),key=len)
Try it online!
Takes input splatted. Will time out for inputs where the first string is long.
The idea is to take substrings of the first strings h to find the longest one that appears in all the remaining strings t. To do so, we recursively branch on removing the first or last character of h.
Python 2, 94 bytes
lambda l:max(set.intersection(*map(g,l)),key=len)
g=lambda s:s and{s}|g(s[1:])|g(s[:-1])or{''}
Try it online!
A more direct method. The auxiliary function g generates the set all substrings of s, and the main function takes the longest one in their intersection.
$endgroup$
add a comment |
$begingroup$
Jelly, 12 6 bytes
Ẇ€f/ṫ0
Try it online!
Thanks to @JonathanAllan for saving 6 bytes!
$endgroup$
$begingroup$
I believeẆ€œ&/Ṫḟ0would do the job and save four bytes since the sub-strings are already ordered by length, hence the filtered result will be; then all that remains is that when there are no matches tail produces a zero, and since we are guaranteed lists of characters we can simply filter those out.
$endgroup$
– Jonathan Allan
Mar 25 at 11:54
$begingroup$
also I thinkœ&/may be replaced byf/here saving another
$endgroup$
– Jonathan Allan
Mar 25 at 12:03
$begingroup$
I submitted a pull request to (hopefully) make the result of reducing an empty list be an empty list (rather than raising a TypeError). If that gets merged in I believe that this answer could then become a six-byter withẆ€f/ṛ/.
$endgroup$
– Jonathan Allan
Mar 25 at 15:59
$begingroup$
@JonathanAllan sounds good. Thanks for the other tips - hope you were happy for me to incorporate them.
$endgroup$
– Nick Kennedy
Mar 25 at 16:25
$begingroup$
Yes, my reason for those comments was to allow you to incorporate the ideas into your post.
$endgroup$
– Jonathan Allan
Mar 25 at 16:39
|
show 1 more comment
$begingroup$
Ruby 2.6, 76 59 54 bytes
->a{*w=a;w.find{|r|w<<r.chop<<r[1..];a.all?{|s|s[r]}}}
Try it online! - Ruby 2.5 version (56 bytes)
How?
Create a list of potential matches, initially set to the original array. Iterate on the list, and if a string does not match, add 2 new strings to the tail of the list, chopping off the first or the last character. At the end a match (eventually an empty string) will be found.
Thanks Kirill L for -2 bytes and histocrat for another -2
$endgroup$
add a comment |
$begingroup$
R, 119 116 108 106 bytes
function(S,`?`=nchar,K=max(?S),s=Reduce(intersect,lapply(S,substring,0:K,rep(0:K,e=K+1))))s[which.max(?s)]
Try it online!
Find all substrings of each string, find the intersection of each list of substrings, then finally return (one of) the longest.
-3 bytes thanks to Kirill L.
-8 bytes using lapply instead of Map
-2 bytes thanks to Kirill L. again, removing braces
$endgroup$
$begingroup$
I don't have time to check, but if I'm not mistaken, 2 occurrences ofncharare enough to save something by declaringncharas an unary operator.
$endgroup$
– Kirill L.
Mar 25 at 16:19
$begingroup$
@KirillL. yes, it is shorter by 2 bytes. Thanks! Aliasinglistsimilarly gives us -3 bytes.
$endgroup$
– Giuseppe
Mar 25 at 16:27
$begingroup$
You can also drop braces for another -2
$endgroup$
– Kirill L.
Mar 25 at 22:06
$begingroup$
@KirillL. thanks! I'm a bit worried I'm going to start doing that with production code...
$endgroup$
– Giuseppe
Mar 25 at 22:15
$begingroup$
that's the problem with golfing a language you use every day
$endgroup$
– MickyT
Mar 25 at 22:52
add a comment |
$begingroup$
05AB1E, 14 9 8 bytes
€Œ.«ÃéθJ
-6 bytes thanks to @Adnan.
Try it online or verify all test cases.
Explanation:
€Œ # Get the substring of each string in the (implicit) input-list
.« # Right-reduce this list of list of strings by:
à # Only keep all the strings that are present in both list of strings
é # Sort by length
θ # And pop and push its last item
# The substrings exclude empty items, so if after the reduce an empty list remains,
# the last item will also be an empty list,
J # which will become an empty string after a join
# (after which the result is output implicitly)
$endgroup$
1
$begingroup$
I think€Œ.«Ãõªéθshould work for 9 bytes.
$endgroup$
– Adnan
Mar 25 at 14:22
$begingroup$
@Adnan Wait, we do have a reduce.. How did I miss that. :S I triedÅ«Ã, but didn't realize I should have used.«Ãinstead.. Thanks!
$endgroup$
– Kevin Cruijssen
Mar 25 at 14:25
1
$begingroup$
Actually, I think€Œ.«ÃéθJshould work for 8.
$endgroup$
– Adnan
Mar 25 at 19:58
add a comment |
$begingroup$
Zsh, 126 123 117 112 111 bytes
-3 bytes from arithmetic for, -6 bytes from implicit "$@" (thanks roblogic), -5 bytes from removing unneeded { }, -1 byte from short form of for
for l
{a= i=
for ((;i++<$#l**2;))a+=($l[1+i/$#l,1+i%$#l])
b=(${${b-$a}:*a})}
for s ($b)
(($#x<$#s))&&x=$s
<<<$x
Try it online!
We read all possible substrings into the arraya, and then set b to the intersection of the arrays a and b. The construct ${b-$a} will only substitue $a on the first iteration: Unlike its sibling expansion ${b:-$a}, it will not substitute when b is set but empty.
for l; { # implicit "$@"
a= i= # empty a and i
for (( ; i++ < $#l**2; )) # compound double loop using div/mod
a+=( $l[1+i/$#l,1+i%$#l] ) # append to a all possible substrings of the given line
# 1+i/$#l # 1,1,1..., 1,1,2,2,2,... ..., n,n
# 1+i%$#l # 1,2,3...,n-1,n,1,2,3,... ...,n-1,n
# a+=( $l[ , ] ) # append that substring to the array
b=( ${${b-$a}:*a} )
# ${b-$a} # if b is unset substitute $a
# ${ :*a} # take common elements of ${b-$a} and $a
# b=( ) # set b to those elements
}
for s ($b) # for every common substring
(( $#x < $#s )) && x=$s # if the current word is longer, use it
<<<$x # print to stdout
New contributor
GammaFunction is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
$begingroup$
How does this bit work?a+=( $l[1+i/$#l,1+i%$#l] )
$endgroup$
– roblogic
Mar 26 at 12:44
1
$begingroup$
@roblogic I think I explained it better now, check the edit. The idea is to loop to n^2 and use / and % instead of using 2 nestedforloops
$endgroup$
– GammaFunction
Mar 26 at 13:13
1
$begingroup$
you might be able to cutfor l in "$@"to simplyfor l;- it's a bash trick
$endgroup$
– roblogic
Mar 26 at 16:41
$begingroup$
i gotta say, zsh is so much more elegant than bash. There's nothing analogous to this nice array comparison AFAIKb=(${${b-$a}:*a})}
$endgroup$
– roblogic
2 days ago
1
$begingroup$
There's some neat things you can do with it, and it isn't all that popular. That translates into me adding a zsh answer to most questions I come across. :P If you want to learn zsh, I recommendman zshexpnandman zshparamespecially. I always have them open when writing an answer.
$endgroup$
– GammaFunction
2 days ago
add a comment |
$begingroup$
Perl 6, 62 bytes
{~sort(-*.comb,keys [∩] .map(*.comb[^*X.. ^*+1]>>.join))[0]}
Try it online!
I'm a little annoyed the Perl 6 can't do set operations on lists of lists, which is why there's an extra .comb and >> in there. Another annoying thing is that max can't take an function for how to compare items, meaning I have to user sort instead.
$endgroup$
3
$begingroup$
maxcan take such a function (arity 1 though), either by position when called in OO mode, or a named:byargument in procedural mode.
$endgroup$
– Ven
Mar 25 at 9:31
add a comment |
$begingroup$
Haskell, 80 bytes
import Data.List
f(x:r)=last$sortOn(0<$)[s|s<-inits=<<tails x,all(isInfixOf s)r]
Try it online!
Get all suffixes (tails) of the first word x in the list and take all prefixes (inits) of those suffixes to get all substrings s of x. Keep each s that isInfixOf all strings in the remaining list r. Sort those substrings by length (using the (0<$) trick) and return the last.
$endgroup$
add a comment |
$begingroup$
TSQL query, 154 bytes
USE master
DECLARE @ table(a varchar(999)collate Latin1_General_CS_AI,i int identity)
INSERT @ values('string'),('stRIng');
SELECT top 1x FROM(SELECT
distinct substring(a,f.number,g.number)x,i
FROM spt_values f,spt_values g,@ WHERE'L'=g.type)D
GROUP BY x ORDER BY-sum(i),-len(x)
Try it online
Made case sensitive by declaring the column 'a' with collation containing CS (case sensitive).
Splitting all strings from 2540 starting positions(many identical) but the useful values range between 1 and 2070 and ending 0 to 22 characters after starting position, the end position could be longer by changing the type to 'P' instead of 'L', but would cripple performance.
These distinct strings within each rownumber are counted. The highest count will always be equal to the number of rows in the table variable '@'. Reversing the order on the same count will leave the substring with most matches on top of the results followed by reversed length of the substring will leave longest match with most matches on top. The query only select the top 1 row.
In order to get all answers, change the first part of the query to
SELECT top 1with ties x FROM
$endgroup$
add a comment |
$begingroup$
C# (Visual C# Interactive Compiler), 320 257 bytes
l=>(string.Join(",",l.Select(s=>new int[s.Length*s.Length*2].Select((i,j)=>string.Concat(s.Skip(j/-~s.Length).Take(j%-~s.Length))))
.Aggregate((a,b)=>a.Intersect(b)).GroupBy(x=>x.Length).OrderBy(x =>x.Key).LastOrDefault()?.Select(y=>y)??new List<string>()));
Try it online!
Props to @Expired Data and @dana
New contributor
Innat3 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
$begingroup$
You can just return the string from a function. So in Interactive compiler it might look something like this: 294 bytes
$endgroup$
– Expired Data
Mar 25 at 16:45
1
$begingroup$
Here's the solution golfed down some bytes 215 bytes
$endgroup$
– Expired Data
Mar 25 at 17:00
$begingroup$
@ExpiredData ah perfect this is the example I needed :)
$endgroup$
– Innat3
Mar 26 at 8:22
$begingroup$
186
$endgroup$
– dana
2 days ago
$begingroup$
184
$endgroup$
– Embodiment of Ignorance
2 days ago
add a comment |
$begingroup$
Japt -h, 8 bytes
(I could knock off the last 3 bytes and use the -Fh flag instead but I'm not a fan of using -F)
mã rf iP
Try it or run all test cases
mã rf iP :Implicit input of array
m :Map
ã : Substrings
r :Reduce by
f : Filter, keeping only elements that appear in both arrays
i :Prepend
P : An empty string
:Implicit output of last element
$endgroup$
add a comment |
$begingroup$
Japt v2.0a0 -hF, 8 bytes
Îã f@eøX
Thanks to Shaggy for saving 3 bytes
Try it
Îã //Generate all substrings of the first string
f@ //Filter; keep the substrings that satisfy the following predicate:
e // If all strings of the input...
øX // Contain this substring, then keep it
-h //Take last element
-F //If last element is undefined, default to empty string
$endgroup$
$begingroup$
You shouldn't need to sort by length at the end, saving 3 bytes. Also,-Fdefaults to the empty string.
$endgroup$
– Shaggy
Mar 25 at 11:49
add a comment |
$begingroup$
Retina 0.8.2, 48 bytes
M&!`(?<=^.*)(.+)(?=(.*n.*1)*.*$)
O#$^`
$.&
1G`
Try it online! Explanation:
M&!`(?<=^.*)(.+)(?=(.*n.*1)*.*$)
For each suffix of the first string, find the longest prefix that's also a substring of all of the other strings. List all of those suffix prefixes (i.e. substrings). If there are no matching substrings, we just end up with the empty string, which is what we want anyway.
O#$^`
$.&
Sort the substrings in reverse order of length.
1G`
Keep only the first, i.e. the longest substring.
$endgroup$
$begingroup$
Letnis number of argument strings. Then(?=(.*n.*1)*.*$)should be(?=(.*n.*1){n-1}.*$), isn't it? Test case:["very", "different", "much"] -> [""]
$endgroup$
– mazzy
2 days ago
1
$begingroup$
@mazzy I don't see the problem: Try it online!
$endgroup$
– Neil
2 days ago
$begingroup$
it is not a problem. with{n}you could remove start and end patterns and keep(.+)(?=(.*n.*1){n}if Retina allows to writenshorter than(?<=^.*).*$
$endgroup$
– mazzy
2 days ago
$begingroup$
@mazzy I can't in Retina 0.8.2, and in Retina 1 I'd have to mess around with eval, which would probably be longer anyway.
$endgroup$
– Neil
2 days ago
add a comment |
$begingroup$
Python 3, 137 bytes
def a(b):c=[[d[f:e]for e in range(len(d)+1)for f in range(e+1)]for d in b];return max([i for i in c[0]if all(i in j for j in c)],key=len)
Try it online!
New contributor
Artemis Fowl is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
$begingroup$
You may want to use single spaces as indentation instead of 4 that seems to shave more than 100 bytes.
$endgroup$
– Shieru Asakoto
Mar 25 at 1:21
$begingroup$
@JoKing tio.run/…
$endgroup$
– Artemis Fowl
Mar 25 at 2:20
$begingroup$
Right, here's a fixed version of the 135 byte program
$endgroup$
– Jo King
Mar 25 at 2:29
add a comment |
$begingroup$
Python 2, 103 bytes
lambda b:max(reduce(set.__and__,[{d[f:e]for e in range(len(d)+2)for f in range(e)}for d in b]),key=len)
Try it online!
This is an anonymous lambda that transforms each element into the set of all substrings, then reduces it by set intersection (set.__and__) and then returns the max element by length.
$endgroup$
$begingroup$
1 byte shorter withset.intersection.
$endgroup$
– ovs
Mar 25 at 11:45
add a comment |
$begingroup$
C# (Visual C# Interactive Compiler), 147 145 bytes
a=>{int i=0,j,m=0,k=a[0].Length;string s="",d=s;for(;i<k;i++)for(j=m;j++<k-i;)if(a.All(y=>y.Contains(s=a[0].Substring(i,j)))){m=j;d=s;}return d;}
Try it online!
$endgroup$
add a comment |
$begingroup$
Perl 5 (-aln0777F/n/ -M5.01 -MList::util=max), 99 bytes
may be golfed more certainly
map/(.+)(?!.*1)(?{$h{$&}++})(?!)/,@F;say for grep{y///c==max map y///c,@b}@b=grep@F==$h{$_},keys%h
TIO
$endgroup$
add a comment |
$begingroup$
JavaScript (ES6), 98 92 bytes
a=>(g=b=s=>a.every(x=>~x.indexOf(s))?b=b[s.length]?b:s:g(s.slice(0,-1,g(s.slice(1)))))(a[0])
Try it online!
$endgroup$
add a comment |
$begingroup$
Bash 4+, 295... 178 bytes
Not pretty but at least it works.
Try it Online
-37 by general cleaning up ;
-52 by plagiarising from the zsh answer ;
-26 by replacing array with a loop ;
-2 thanks to GammaFunction
for l;{ d=${#l}
for((i=0;i<d**2;i++)){ a="${l:i/d:1+i%d}" k=
for n;{ [[ $n =~ $a ]]&&((k++));}
((k-$#))||b+=("$a");};}
for e in "${b[@]}";do((${#e}>${#f}))&&f="$e";done
echo "$f"
Here's the original ungolfed script with comments
New contributor
roblogic is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
1
$begingroup$
Save 2 more: You can replace((k==$#))&&with((k-$#))||. This also lets you usek=instead of setting it to 0.
$endgroup$
– GammaFunction
2 days ago
1
$begingroup$
I think "Not pretty but at least it works" is the MO for bash scripts :)
$endgroup$
– joeytwiddle
2 days ago
add a comment |
$begingroup$
Java (JDK), 176 bytes
a->{int l=a.get(0).length(),m=0,i=0,j;var r="";for(;i<l;i++)for(j=i;j++<l;){var s=a.get(0).substring(i,j);if(j-i>m&a.stream().allMatch(x->x.contains(s))){r=s;m=j-i;}}return r;}
Try it online!
This is a rather naive implementation.
$endgroup$
add a comment |
$begingroup$
Red, 266 174 bytes
func[b][l: length? s: b/1 n: 1 until[i: 1 loop n[t: copy/part at s i l r: on foreach u
next b[r: r and(none <> find/case u t)]if r[return t]i: i + 1]n: n + 1 1 > l: l - 1]""]
Try it online!
Changed the recursion to iteration and got rid of the sorting.
$endgroup$
add a comment |
$begingroup$
Perl 5, 87 bytes
my$r;"$&@_"=~/(.{@{[$r=~y,,,c]},}).*(n.*1.*){@{[@_-1]}}/ and$r=$1while$_[0]=~s,.,,;$r
Try it online!
$endgroup$
add a comment |
$begingroup$
JavaScript (Node.js), 106 bytes
a=>(F=(l,n,w=a[0].substr(n,l))=>l?n<0?F(--l,L-l):a.some(y=>y.indexOf(w)<0)?F(l,n-1):w:"")(L=a[0].length,0)
Try it online!
a=>( // Main function
F=( // Helper function to run through all substrings in a[0]
l, // Length
n, // Start position
w=a[0].substr(n,l) // The substring
)=>
l? // If l > 0:
n<0? // If n < 0:
F(--l,L-l) // Check another length
:a.some( // If n >= 0:
y=>y.indexOf(w)<0 // Check whether there is any string not containing the substring
// (indexOf used because of presence of regex special characters)
)? // If so:
F(l,n-1) // Check another substring
:w // If not, return this substring and terminate
// (This function checks from the longest substring possible, so
// it is safe to return right here)
:"" // If l <= 0: Return empty string (no common substring)
)(
L=a[0].length, // Starts from length = the whole length of a[0]
0 // And start position = 0
)
$endgroup$
add a comment |
$begingroup$
Gaia, 15 bytes
eḋ¦&⊢⟨:l¦:⌉=¦⟩∇
Try it online!
e | eval as code
ḋ¦ | find all non-empty substrings
&⊢ | Reduce by set intersection
∇ | and return the first element where
⟨:l¦:⌉=¦⟩ | the length is equal to the max length$endgroup$
add a comment |
$begingroup$
PowerShell, 165 163 87 bytes
-76 bytes thanks to Nail for the awesome regexp.
"$($args-join'
'|sls "(?<=^.*)(.+)(?=(.*n.*1)*.*$)"-a -ca|% m*|sort Le*|select -l 1)"
Try it online!
Less golfed:
$multilineArgs = $args-join"`n"
$matches = $multilineArgs|sls "(?<=^.*)(.+)(?=(.*n.*1)*.*$)" -AllMatches -CaseSensitive|% matches
$longestOrNull = $matches|sort Length|select -Last 1
"$longestOrNull"
$endgroup$
add a comment |
$begingroup$
Charcoal, 30 bytes
≔⊟θη≔⁰ζFLη«≔✂ηζ⊕ι¹ε¿⬤θ№κεPε≦⊕ζ
Try it online! Link is to verbose version of code. This algorithm is more efficient as well as shorter than generating all substrings. Explanation:
≔⊟θη
Pop the last string from the input list into a variable.
≔⁰ζ
Zero out the substring start index.
FLη«
Loop over all possible substring end indices. (Actually this loops from 0 excluding the length, so the value is adjusted later.)
≔✂ηζ⊕ι¹ε
Obtain the current substring.
¿⬤θ№κε
Check whether this substring is contained in all of the other input strings.
Pε
If it is then overprint any previously output substring.
≦⊕ζ
Otherwise try incrementing the substring start index.
$endgroup$
add a comment |
$begingroup$
JavaScript (Node.js), 90 bytes
f=(a,s=e=0,w='')=>a[0][e]?f(a,s+(r=a.some(x=>!x.includes(t),t=a[0].slice(s,++e))),r?w:t):w
Try it online! Test cases shamelessly stolen from @Arnauld. Port of my Charcoal answer.
$endgroup$
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "200"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodegolf.stackexchange.com%2fquestions%2f182134%2fgreatest-common-substring%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
28 Answers
28
active
oldest
votes
28 Answers
28
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
Brachylog (v2), 3 9 bytes
{sᵛ}ᶠlᵒtw
Try it online!
Full program. Input from standard input (as a JSON-style list of strings), output to standard output.
Explanation
{sᵛ}ᶠlᵒtw
s Find a substring
ᵛ of every element {of the input}; the same one for each
{ }ᶠ Convert generator to list
lᵒt Take list element with maximum length
w Output it
Apparently, the tiebreak order on s is not what it is in nearly everything else in Brachylog, so we need to manually override it to produce the longest output. (That's a bit frustrating: four extra characters for the override, plus two grouping characters because Brachylog doesn't parse two metapredicates in a row.)
Brachylog's s doesn't return empty substrings, so we need a bit of a trick to get around that: instead of making a function submission (which is what's normally done), we write a full program, outputting to standard output. That way, if there's a common substring, we just output it, and we're done. If there isn't a common substring, the program errors out – but it still prints nothing to standard output, thus it outputs the null string as intended.
$endgroup$
1
$begingroup$
I tried this with the input ["many inpuabts", "any inabputs", "ny iabii", "yanabny"]. I expected the results ab and ny. But only got the result a. Am I doing something wrong ?
$endgroup$
– t-clausen.dk
Mar 25 at 11:54
$begingroup$
Ugh, seems I remembered the tiebreak order forswrong, and overriding the tiebreak order is rather expensive byte-wise. Doing that now anyway, though, because it's important for the answer to be correct. Somehow none of the test cases I tried noticed the difference.
$endgroup$
– ais523
Mar 25 at 12:21
$begingroup$
@ais523 The ordersproduces substrings is by first giving all prefixes of the input (longest first), then dropping the first one and repeat
$endgroup$
– Kroppeb
Mar 25 at 17:05
add a comment |
$begingroup$
Brachylog (v2), 3 9 bytes
{sᵛ}ᶠlᵒtw
Try it online!
Full program. Input from standard input (as a JSON-style list of strings), output to standard output.
Explanation
{sᵛ}ᶠlᵒtw
s Find a substring
ᵛ of every element {of the input}; the same one for each
{ }ᶠ Convert generator to list
lᵒt Take list element with maximum length
w Output it
Apparently, the tiebreak order on s is not what it is in nearly everything else in Brachylog, so we need to manually override it to produce the longest output. (That's a bit frustrating: four extra characters for the override, plus two grouping characters because Brachylog doesn't parse two metapredicates in a row.)
Brachylog's s doesn't return empty substrings, so we need a bit of a trick to get around that: instead of making a function submission (which is what's normally done), we write a full program, outputting to standard output. That way, if there's a common substring, we just output it, and we're done. If there isn't a common substring, the program errors out – but it still prints nothing to standard output, thus it outputs the null string as intended.
$endgroup$
1
$begingroup$
I tried this with the input ["many inpuabts", "any inabputs", "ny iabii", "yanabny"]. I expected the results ab and ny. But only got the result a. Am I doing something wrong ?
$endgroup$
– t-clausen.dk
Mar 25 at 11:54
$begingroup$
Ugh, seems I remembered the tiebreak order forswrong, and overriding the tiebreak order is rather expensive byte-wise. Doing that now anyway, though, because it's important for the answer to be correct. Somehow none of the test cases I tried noticed the difference.
$endgroup$
– ais523
Mar 25 at 12:21
$begingroup$
@ais523 The ordersproduces substrings is by first giving all prefixes of the input (longest first), then dropping the first one and repeat
$endgroup$
– Kroppeb
Mar 25 at 17:05
add a comment |
$begingroup$
Brachylog (v2), 3 9 bytes
{sᵛ}ᶠlᵒtw
Try it online!
Full program. Input from standard input (as a JSON-style list of strings), output to standard output.
Explanation
{sᵛ}ᶠlᵒtw
s Find a substring
ᵛ of every element {of the input}; the same one for each
{ }ᶠ Convert generator to list
lᵒt Take list element with maximum length
w Output it
Apparently, the tiebreak order on s is not what it is in nearly everything else in Brachylog, so we need to manually override it to produce the longest output. (That's a bit frustrating: four extra characters for the override, plus two grouping characters because Brachylog doesn't parse two metapredicates in a row.)
Brachylog's s doesn't return empty substrings, so we need a bit of a trick to get around that: instead of making a function submission (which is what's normally done), we write a full program, outputting to standard output. That way, if there's a common substring, we just output it, and we're done. If there isn't a common substring, the program errors out – but it still prints nothing to standard output, thus it outputs the null string as intended.
$endgroup$
Brachylog (v2), 3 9 bytes
{sᵛ}ᶠlᵒtw
Try it online!
Full program. Input from standard input (as a JSON-style list of strings), output to standard output.
Explanation
{sᵛ}ᶠlᵒtw
s Find a substring
ᵛ of every element {of the input}; the same one for each
{ }ᶠ Convert generator to list
lᵒt Take list element with maximum length
w Output it
Apparently, the tiebreak order on s is not what it is in nearly everything else in Brachylog, so we need to manually override it to produce the longest output. (That's a bit frustrating: four extra characters for the override, plus two grouping characters because Brachylog doesn't parse two metapredicates in a row.)
Brachylog's s doesn't return empty substrings, so we need a bit of a trick to get around that: instead of making a function submission (which is what's normally done), we write a full program, outputting to standard output. That way, if there's a common substring, we just output it, and we're done. If there isn't a common substring, the program errors out – but it still prints nothing to standard output, thus it outputs the null string as intended.
edited Mar 25 at 12:24
community wiki
2 revs
ais523
1
$begingroup$
I tried this with the input ["many inpuabts", "any inabputs", "ny iabii", "yanabny"]. I expected the results ab and ny. But only got the result a. Am I doing something wrong ?
$endgroup$
– t-clausen.dk
Mar 25 at 11:54
$begingroup$
Ugh, seems I remembered the tiebreak order forswrong, and overriding the tiebreak order is rather expensive byte-wise. Doing that now anyway, though, because it's important for the answer to be correct. Somehow none of the test cases I tried noticed the difference.
$endgroup$
– ais523
Mar 25 at 12:21
$begingroup$
@ais523 The ordersproduces substrings is by first giving all prefixes of the input (longest first), then dropping the first one and repeat
$endgroup$
– Kroppeb
Mar 25 at 17:05
add a comment |
1
$begingroup$
I tried this with the input ["many inpuabts", "any inabputs", "ny iabii", "yanabny"]. I expected the results ab and ny. But only got the result a. Am I doing something wrong ?
$endgroup$
– t-clausen.dk
Mar 25 at 11:54
$begingroup$
Ugh, seems I remembered the tiebreak order forswrong, and overriding the tiebreak order is rather expensive byte-wise. Doing that now anyway, though, because it's important for the answer to be correct. Somehow none of the test cases I tried noticed the difference.
$endgroup$
– ais523
Mar 25 at 12:21
$begingroup$
@ais523 The ordersproduces substrings is by first giving all prefixes of the input (longest first), then dropping the first one and repeat
$endgroup$
– Kroppeb
Mar 25 at 17:05
1
1
$begingroup$
I tried this with the input ["many inpuabts", "any inabputs", "ny iabii", "yanabny"]. I expected the results ab and ny. But only got the result a. Am I doing something wrong ?
$endgroup$
– t-clausen.dk
Mar 25 at 11:54
$begingroup$
I tried this with the input ["many inpuabts", "any inabputs", "ny iabii", "yanabny"]. I expected the results ab and ny. But only got the result a. Am I doing something wrong ?
$endgroup$
– t-clausen.dk
Mar 25 at 11:54
$begingroup$
Ugh, seems I remembered the tiebreak order for
s wrong, and overriding the tiebreak order is rather expensive byte-wise. Doing that now anyway, though, because it's important for the answer to be correct. Somehow none of the test cases I tried noticed the difference.$endgroup$
– ais523
Mar 25 at 12:21
$begingroup$
Ugh, seems I remembered the tiebreak order for
s wrong, and overriding the tiebreak order is rather expensive byte-wise. Doing that now anyway, though, because it's important for the answer to be correct. Somehow none of the test cases I tried noticed the difference.$endgroup$
– ais523
Mar 25 at 12:21
$begingroup$
@ais523 The order
s produces substrings is by first giving all prefixes of the input (longest first), then dropping the first one and repeat$endgroup$
– Kroppeb
Mar 25 at 17:05
$begingroup$
@ais523 The order
s produces substrings is by first giving all prefixes of the input (longest first), then dropping the first one and repeat$endgroup$
– Kroppeb
Mar 25 at 17:05
add a comment |
$begingroup$
Python 2, 82 bytes
f=lambda h,*t:h and max(h*all(h in s for s in t),f(h[1:],*t),f(h[:-1],*t),key=len)
Try it online!
Takes input splatted. Will time out for inputs where the first string is long.
The idea is to take substrings of the first strings h to find the longest one that appears in all the remaining strings t. To do so, we recursively branch on removing the first or last character of h.
Python 2, 94 bytes
lambda l:max(set.intersection(*map(g,l)),key=len)
g=lambda s:s and{s}|g(s[1:])|g(s[:-1])or{''}
Try it online!
A more direct method. The auxiliary function g generates the set all substrings of s, and the main function takes the longest one in their intersection.
$endgroup$
add a comment |
$begingroup$
Python 2, 82 bytes
f=lambda h,*t:h and max(h*all(h in s for s in t),f(h[1:],*t),f(h[:-1],*t),key=len)
Try it online!
Takes input splatted. Will time out for inputs where the first string is long.
The idea is to take substrings of the first strings h to find the longest one that appears in all the remaining strings t. To do so, we recursively branch on removing the first or last character of h.
Python 2, 94 bytes
lambda l:max(set.intersection(*map(g,l)),key=len)
g=lambda s:s and{s}|g(s[1:])|g(s[:-1])or{''}
Try it online!
A more direct method. The auxiliary function g generates the set all substrings of s, and the main function takes the longest one in their intersection.
$endgroup$
add a comment |
$begingroup$
Python 2, 82 bytes
f=lambda h,*t:h and max(h*all(h in s for s in t),f(h[1:],*t),f(h[:-1],*t),key=len)
Try it online!
Takes input splatted. Will time out for inputs where the first string is long.
The idea is to take substrings of the first strings h to find the longest one that appears in all the remaining strings t. To do so, we recursively branch on removing the first or last character of h.
Python 2, 94 bytes
lambda l:max(set.intersection(*map(g,l)),key=len)
g=lambda s:s and{s}|g(s[1:])|g(s[:-1])or{''}
Try it online!
A more direct method. The auxiliary function g generates the set all substrings of s, and the main function takes the longest one in their intersection.
$endgroup$
Python 2, 82 bytes
f=lambda h,*t:h and max(h*all(h in s for s in t),f(h[1:],*t),f(h[:-1],*t),key=len)
Try it online!
Takes input splatted. Will time out for inputs where the first string is long.
The idea is to take substrings of the first strings h to find the longest one that appears in all the remaining strings t. To do so, we recursively branch on removing the first or last character of h.
Python 2, 94 bytes
lambda l:max(set.intersection(*map(g,l)),key=len)
g=lambda s:s and{s}|g(s[1:])|g(s[:-1])or{''}
Try it online!
A more direct method. The auxiliary function g generates the set all substrings of s, and the main function takes the longest one in their intersection.
answered Mar 25 at 4:26
xnorxnor
93.1k18190448
93.1k18190448
add a comment |
add a comment |
$begingroup$
Jelly, 12 6 bytes
Ẇ€f/ṫ0
Try it online!
Thanks to @JonathanAllan for saving 6 bytes!
$endgroup$
$begingroup$
I believeẆ€œ&/Ṫḟ0would do the job and save four bytes since the sub-strings are already ordered by length, hence the filtered result will be; then all that remains is that when there are no matches tail produces a zero, and since we are guaranteed lists of characters we can simply filter those out.
$endgroup$
– Jonathan Allan
Mar 25 at 11:54
$begingroup$
also I thinkœ&/may be replaced byf/here saving another
$endgroup$
– Jonathan Allan
Mar 25 at 12:03
$begingroup$
I submitted a pull request to (hopefully) make the result of reducing an empty list be an empty list (rather than raising a TypeError). If that gets merged in I believe that this answer could then become a six-byter withẆ€f/ṛ/.
$endgroup$
– Jonathan Allan
Mar 25 at 15:59
$begingroup$
@JonathanAllan sounds good. Thanks for the other tips - hope you were happy for me to incorporate them.
$endgroup$
– Nick Kennedy
Mar 25 at 16:25
$begingroup$
Yes, my reason for those comments was to allow you to incorporate the ideas into your post.
$endgroup$
– Jonathan Allan
Mar 25 at 16:39
|
show 1 more comment
$begingroup$
Jelly, 12 6 bytes
Ẇ€f/ṫ0
Try it online!
Thanks to @JonathanAllan for saving 6 bytes!
$endgroup$
$begingroup$
I believeẆ€œ&/Ṫḟ0would do the job and save four bytes since the sub-strings are already ordered by length, hence the filtered result will be; then all that remains is that when there are no matches tail produces a zero, and since we are guaranteed lists of characters we can simply filter those out.
$endgroup$
– Jonathan Allan
Mar 25 at 11:54
$begingroup$
also I thinkœ&/may be replaced byf/here saving another
$endgroup$
– Jonathan Allan
Mar 25 at 12:03
$begingroup$
I submitted a pull request to (hopefully) make the result of reducing an empty list be an empty list (rather than raising a TypeError). If that gets merged in I believe that this answer could then become a six-byter withẆ€f/ṛ/.
$endgroup$
– Jonathan Allan
Mar 25 at 15:59
$begingroup$
@JonathanAllan sounds good. Thanks for the other tips - hope you were happy for me to incorporate them.
$endgroup$
– Nick Kennedy
Mar 25 at 16:25
$begingroup$
Yes, my reason for those comments was to allow you to incorporate the ideas into your post.
$endgroup$
– Jonathan Allan
Mar 25 at 16:39
|
show 1 more comment
$begingroup$
Jelly, 12 6 bytes
Ẇ€f/ṫ0
Try it online!
Thanks to @JonathanAllan for saving 6 bytes!
$endgroup$
Jelly, 12 6 bytes
Ẇ€f/ṫ0
Try it online!
Thanks to @JonathanAllan for saving 6 bytes!
edited Mar 25 at 18:16
answered Mar 25 at 1:09
Nick KennedyNick Kennedy
1,10648
1,10648
$begingroup$
I believeẆ€œ&/Ṫḟ0would do the job and save four bytes since the sub-strings are already ordered by length, hence the filtered result will be; then all that remains is that when there are no matches tail produces a zero, and since we are guaranteed lists of characters we can simply filter those out.
$endgroup$
– Jonathan Allan
Mar 25 at 11:54
$begingroup$
also I thinkœ&/may be replaced byf/here saving another
$endgroup$
– Jonathan Allan
Mar 25 at 12:03
$begingroup$
I submitted a pull request to (hopefully) make the result of reducing an empty list be an empty list (rather than raising a TypeError). If that gets merged in I believe that this answer could then become a six-byter withẆ€f/ṛ/.
$endgroup$
– Jonathan Allan
Mar 25 at 15:59
$begingroup$
@JonathanAllan sounds good. Thanks for the other tips - hope you were happy for me to incorporate them.
$endgroup$
– Nick Kennedy
Mar 25 at 16:25
$begingroup$
Yes, my reason for those comments was to allow you to incorporate the ideas into your post.
$endgroup$
– Jonathan Allan
Mar 25 at 16:39
|
show 1 more comment
$begingroup$
I believeẆ€œ&/Ṫḟ0would do the job and save four bytes since the sub-strings are already ordered by length, hence the filtered result will be; then all that remains is that when there are no matches tail produces a zero, and since we are guaranteed lists of characters we can simply filter those out.
$endgroup$
– Jonathan Allan
Mar 25 at 11:54
$begingroup$
also I thinkœ&/may be replaced byf/here saving another
$endgroup$
– Jonathan Allan
Mar 25 at 12:03
$begingroup$
I submitted a pull request to (hopefully) make the result of reducing an empty list be an empty list (rather than raising a TypeError). If that gets merged in I believe that this answer could then become a six-byter withẆ€f/ṛ/.
$endgroup$
– Jonathan Allan
Mar 25 at 15:59
$begingroup$
@JonathanAllan sounds good. Thanks for the other tips - hope you were happy for me to incorporate them.
$endgroup$
– Nick Kennedy
Mar 25 at 16:25
$begingroup$
Yes, my reason for those comments was to allow you to incorporate the ideas into your post.
$endgroup$
– Jonathan Allan
Mar 25 at 16:39
$begingroup$
I believe
Ẇ€œ&/Ṫḟ0 would do the job and save four bytes since the sub-strings are already ordered by length, hence the filtered result will be; then all that remains is that when there are no matches tail produces a zero, and since we are guaranteed lists of characters we can simply filter those out.$endgroup$
– Jonathan Allan
Mar 25 at 11:54
$begingroup$
I believe
Ẇ€œ&/Ṫḟ0 would do the job and save four bytes since the sub-strings are already ordered by length, hence the filtered result will be; then all that remains is that when there are no matches tail produces a zero, and since we are guaranteed lists of characters we can simply filter those out.$endgroup$
– Jonathan Allan
Mar 25 at 11:54
$begingroup$
also I think
œ&/ may be replaced by f/ here saving another$endgroup$
– Jonathan Allan
Mar 25 at 12:03
$begingroup$
also I think
œ&/ may be replaced by f/ here saving another$endgroup$
– Jonathan Allan
Mar 25 at 12:03
$begingroup$
I submitted a pull request to (hopefully) make the result of reducing an empty list be an empty list (rather than raising a TypeError). If that gets merged in I believe that this answer could then become a six-byter with
Ẇ€f/ṛ/.$endgroup$
– Jonathan Allan
Mar 25 at 15:59
$begingroup$
I submitted a pull request to (hopefully) make the result of reducing an empty list be an empty list (rather than raising a TypeError). If that gets merged in I believe that this answer could then become a six-byter with
Ẇ€f/ṛ/.$endgroup$
– Jonathan Allan
Mar 25 at 15:59
$begingroup$
@JonathanAllan sounds good. Thanks for the other tips - hope you were happy for me to incorporate them.
$endgroup$
– Nick Kennedy
Mar 25 at 16:25
$begingroup$
@JonathanAllan sounds good. Thanks for the other tips - hope you were happy for me to incorporate them.
$endgroup$
– Nick Kennedy
Mar 25 at 16:25
$begingroup$
Yes, my reason for those comments was to allow you to incorporate the ideas into your post.
$endgroup$
– Jonathan Allan
Mar 25 at 16:39
$begingroup$
Yes, my reason for those comments was to allow you to incorporate the ideas into your post.
$endgroup$
– Jonathan Allan
Mar 25 at 16:39
|
show 1 more comment
$begingroup$
Ruby 2.6, 76 59 54 bytes
->a{*w=a;w.find{|r|w<<r.chop<<r[1..];a.all?{|s|s[r]}}}
Try it online! - Ruby 2.5 version (56 bytes)
How?
Create a list of potential matches, initially set to the original array. Iterate on the list, and if a string does not match, add 2 new strings to the tail of the list, chopping off the first or the last character. At the end a match (eventually an empty string) will be found.
Thanks Kirill L for -2 bytes and histocrat for another -2
$endgroup$
add a comment |
$begingroup$
Ruby 2.6, 76 59 54 bytes
->a{*w=a;w.find{|r|w<<r.chop<<r[1..];a.all?{|s|s[r]}}}
Try it online! - Ruby 2.5 version (56 bytes)
How?
Create a list of potential matches, initially set to the original array. Iterate on the list, and if a string does not match, add 2 new strings to the tail of the list, chopping off the first or the last character. At the end a match (eventually an empty string) will be found.
Thanks Kirill L for -2 bytes and histocrat for another -2
$endgroup$
add a comment |
$begingroup$
Ruby 2.6, 76 59 54 bytes
->a{*w=a;w.find{|r|w<<r.chop<<r[1..];a.all?{|s|s[r]}}}
Try it online! - Ruby 2.5 version (56 bytes)
How?
Create a list of potential matches, initially set to the original array. Iterate on the list, and if a string does not match, add 2 new strings to the tail of the list, chopping off the first or the last character. At the end a match (eventually an empty string) will be found.
Thanks Kirill L for -2 bytes and histocrat for another -2
$endgroup$
Ruby 2.6, 76 59 54 bytes
->a{*w=a;w.find{|r|w<<r.chop<<r[1..];a.all?{|s|s[r]}}}
Try it online! - Ruby 2.5 version (56 bytes)
How?
Create a list of potential matches, initially set to the original array. Iterate on the list, and if a string does not match, add 2 new strings to the tail of the list, chopping off the first or the last character. At the end a match (eventually an empty string) will be found.
Thanks Kirill L for -2 bytes and histocrat for another -2
edited Mar 25 at 19:08
answered Mar 25 at 8:05
G BG B
8,1261429
8,1261429
add a comment |
add a comment |
$begingroup$
R, 119 116 108 106 bytes
function(S,`?`=nchar,K=max(?S),s=Reduce(intersect,lapply(S,substring,0:K,rep(0:K,e=K+1))))s[which.max(?s)]
Try it online!
Find all substrings of each string, find the intersection of each list of substrings, then finally return (one of) the longest.
-3 bytes thanks to Kirill L.
-8 bytes using lapply instead of Map
-2 bytes thanks to Kirill L. again, removing braces
$endgroup$
$begingroup$
I don't have time to check, but if I'm not mistaken, 2 occurrences ofncharare enough to save something by declaringncharas an unary operator.
$endgroup$
– Kirill L.
Mar 25 at 16:19
$begingroup$
@KirillL. yes, it is shorter by 2 bytes. Thanks! Aliasinglistsimilarly gives us -3 bytes.
$endgroup$
– Giuseppe
Mar 25 at 16:27
$begingroup$
You can also drop braces for another -2
$endgroup$
– Kirill L.
Mar 25 at 22:06
$begingroup$
@KirillL. thanks! I'm a bit worried I'm going to start doing that with production code...
$endgroup$
– Giuseppe
Mar 25 at 22:15
$begingroup$
that's the problem with golfing a language you use every day
$endgroup$
– MickyT
Mar 25 at 22:52
add a comment |
$begingroup$
R, 119 116 108 106 bytes
function(S,`?`=nchar,K=max(?S),s=Reduce(intersect,lapply(S,substring,0:K,rep(0:K,e=K+1))))s[which.max(?s)]
Try it online!
Find all substrings of each string, find the intersection of each list of substrings, then finally return (one of) the longest.
-3 bytes thanks to Kirill L.
-8 bytes using lapply instead of Map
-2 bytes thanks to Kirill L. again, removing braces
$endgroup$
$begingroup$
I don't have time to check, but if I'm not mistaken, 2 occurrences ofncharare enough to save something by declaringncharas an unary operator.
$endgroup$
– Kirill L.
Mar 25 at 16:19
$begingroup$
@KirillL. yes, it is shorter by 2 bytes. Thanks! Aliasinglistsimilarly gives us -3 bytes.
$endgroup$
– Giuseppe
Mar 25 at 16:27
$begingroup$
You can also drop braces for another -2
$endgroup$
– Kirill L.
Mar 25 at 22:06
$begingroup$
@KirillL. thanks! I'm a bit worried I'm going to start doing that with production code...
$endgroup$
– Giuseppe
Mar 25 at 22:15
$begingroup$
that's the problem with golfing a language you use every day
$endgroup$
– MickyT
Mar 25 at 22:52
add a comment |
$begingroup$
R, 119 116 108 106 bytes
function(S,`?`=nchar,K=max(?S),s=Reduce(intersect,lapply(S,substring,0:K,rep(0:K,e=K+1))))s[which.max(?s)]
Try it online!
Find all substrings of each string, find the intersection of each list of substrings, then finally return (one of) the longest.
-3 bytes thanks to Kirill L.
-8 bytes using lapply instead of Map
-2 bytes thanks to Kirill L. again, removing braces
$endgroup$
R, 119 116 108 106 bytes
function(S,`?`=nchar,K=max(?S),s=Reduce(intersect,lapply(S,substring,0:K,rep(0:K,e=K+1))))s[which.max(?s)]
Try it online!
Find all substrings of each string, find the intersection of each list of substrings, then finally return (one of) the longest.
-3 bytes thanks to Kirill L.
-8 bytes using lapply instead of Map
-2 bytes thanks to Kirill L. again, removing braces
edited Mar 25 at 22:13
answered Mar 25 at 16:08
GiuseppeGiuseppe
17.2k31152
17.2k31152
$begingroup$
I don't have time to check, but if I'm not mistaken, 2 occurrences ofncharare enough to save something by declaringncharas an unary operator.
$endgroup$
– Kirill L.
Mar 25 at 16:19
$begingroup$
@KirillL. yes, it is shorter by 2 bytes. Thanks! Aliasinglistsimilarly gives us -3 bytes.
$endgroup$
– Giuseppe
Mar 25 at 16:27
$begingroup$
You can also drop braces for another -2
$endgroup$
– Kirill L.
Mar 25 at 22:06
$begingroup$
@KirillL. thanks! I'm a bit worried I'm going to start doing that with production code...
$endgroup$
– Giuseppe
Mar 25 at 22:15
$begingroup$
that's the problem with golfing a language you use every day
$endgroup$
– MickyT
Mar 25 at 22:52
add a comment |
$begingroup$
I don't have time to check, but if I'm not mistaken, 2 occurrences ofncharare enough to save something by declaringncharas an unary operator.
$endgroup$
– Kirill L.
Mar 25 at 16:19
$begingroup$
@KirillL. yes, it is shorter by 2 bytes. Thanks! Aliasinglistsimilarly gives us -3 bytes.
$endgroup$
– Giuseppe
Mar 25 at 16:27
$begingroup$
You can also drop braces for another -2
$endgroup$
– Kirill L.
Mar 25 at 22:06
$begingroup$
@KirillL. thanks! I'm a bit worried I'm going to start doing that with production code...
$endgroup$
– Giuseppe
Mar 25 at 22:15
$begingroup$
that's the problem with golfing a language you use every day
$endgroup$
– MickyT
Mar 25 at 22:52
$begingroup$
I don't have time to check, but if I'm not mistaken, 2 occurrences of
nchar are enough to save something by declaring nchar as an unary operator.$endgroup$
– Kirill L.
Mar 25 at 16:19
$begingroup$
I don't have time to check, but if I'm not mistaken, 2 occurrences of
nchar are enough to save something by declaring nchar as an unary operator.$endgroup$
– Kirill L.
Mar 25 at 16:19
$begingroup$
@KirillL. yes, it is shorter by 2 bytes. Thanks! Aliasing
list similarly gives us -3 bytes.$endgroup$
– Giuseppe
Mar 25 at 16:27
$begingroup$
@KirillL. yes, it is shorter by 2 bytes. Thanks! Aliasing
list similarly gives us -3 bytes.$endgroup$
– Giuseppe
Mar 25 at 16:27
$begingroup$
You can also drop braces for another -2
$endgroup$
– Kirill L.
Mar 25 at 22:06
$begingroup$
You can also drop braces for another -2
$endgroup$
– Kirill L.
Mar 25 at 22:06
$begingroup$
@KirillL. thanks! I'm a bit worried I'm going to start doing that with production code...
$endgroup$
– Giuseppe
Mar 25 at 22:15
$begingroup$
@KirillL. thanks! I'm a bit worried I'm going to start doing that with production code...
$endgroup$
– Giuseppe
Mar 25 at 22:15
$begingroup$
that's the problem with golfing a language you use every day
$endgroup$
– MickyT
Mar 25 at 22:52
$begingroup$
that's the problem with golfing a language you use every day
$endgroup$
– MickyT
Mar 25 at 22:52
add a comment |
$begingroup$
05AB1E, 14 9 8 bytes
€Œ.«ÃéθJ
-6 bytes thanks to @Adnan.
Try it online or verify all test cases.
Explanation:
€Œ # Get the substring of each string in the (implicit) input-list
.« # Right-reduce this list of list of strings by:
à # Only keep all the strings that are present in both list of strings
é # Sort by length
θ # And pop and push its last item
# The substrings exclude empty items, so if after the reduce an empty list remains,
# the last item will also be an empty list,
J # which will become an empty string after a join
# (after which the result is output implicitly)
$endgroup$
1
$begingroup$
I think€Œ.«Ãõªéθshould work for 9 bytes.
$endgroup$
– Adnan
Mar 25 at 14:22
$begingroup$
@Adnan Wait, we do have a reduce.. How did I miss that. :S I triedÅ«Ã, but didn't realize I should have used.«Ãinstead.. Thanks!
$endgroup$
– Kevin Cruijssen
Mar 25 at 14:25
1
$begingroup$
Actually, I think€Œ.«ÃéθJshould work for 8.
$endgroup$
– Adnan
Mar 25 at 19:58
add a comment |
$begingroup$
05AB1E, 14 9 8 bytes
€Œ.«ÃéθJ
-6 bytes thanks to @Adnan.
Try it online or verify all test cases.
Explanation:
€Œ # Get the substring of each string in the (implicit) input-list
.« # Right-reduce this list of list of strings by:
à # Only keep all the strings that are present in both list of strings
é # Sort by length
θ # And pop and push its last item
# The substrings exclude empty items, so if after the reduce an empty list remains,
# the last item will also be an empty list,
J # which will become an empty string after a join
# (after which the result is output implicitly)
$endgroup$
1
$begingroup$
I think€Œ.«Ãõªéθshould work for 9 bytes.
$endgroup$
– Adnan
Mar 25 at 14:22
$begingroup$
@Adnan Wait, we do have a reduce.. How did I miss that. :S I triedÅ«Ã, but didn't realize I should have used.«Ãinstead.. Thanks!
$endgroup$
– Kevin Cruijssen
Mar 25 at 14:25
1
$begingroup$
Actually, I think€Œ.«ÃéθJshould work for 8.
$endgroup$
– Adnan
Mar 25 at 19:58
add a comment |
$begingroup$
05AB1E, 14 9 8 bytes
€Œ.«ÃéθJ
-6 bytes thanks to @Adnan.
Try it online or verify all test cases.
Explanation:
€Œ # Get the substring of each string in the (implicit) input-list
.« # Right-reduce this list of list of strings by:
à # Only keep all the strings that are present in both list of strings
é # Sort by length
θ # And pop and push its last item
# The substrings exclude empty items, so if after the reduce an empty list remains,
# the last item will also be an empty list,
J # which will become an empty string after a join
# (after which the result is output implicitly)
$endgroup$
05AB1E, 14 9 8 bytes
€Œ.«ÃéθJ
-6 bytes thanks to @Adnan.
Try it online or verify all test cases.
Explanation:
€Œ # Get the substring of each string in the (implicit) input-list
.« # Right-reduce this list of list of strings by:
à # Only keep all the strings that are present in both list of strings
é # Sort by length
θ # And pop and push its last item
# The substrings exclude empty items, so if after the reduce an empty list remains,
# the last item will also be an empty list,
J # which will become an empty string after a join
# (after which the result is output implicitly)
edited Mar 26 at 7:02
answered Mar 25 at 10:53
Kevin CruijssenKevin Cruijssen
41.9k568217
41.9k568217
1
$begingroup$
I think€Œ.«Ãõªéθshould work for 9 bytes.
$endgroup$
– Adnan
Mar 25 at 14:22
$begingroup$
@Adnan Wait, we do have a reduce.. How did I miss that. :S I triedÅ«Ã, but didn't realize I should have used.«Ãinstead.. Thanks!
$endgroup$
– Kevin Cruijssen
Mar 25 at 14:25
1
$begingroup$
Actually, I think€Œ.«ÃéθJshould work for 8.
$endgroup$
– Adnan
Mar 25 at 19:58
add a comment |
1
$begingroup$
I think€Œ.«Ãõªéθshould work for 9 bytes.
$endgroup$
– Adnan
Mar 25 at 14:22
$begingroup$
@Adnan Wait, we do have a reduce.. How did I miss that. :S I triedÅ«Ã, but didn't realize I should have used.«Ãinstead.. Thanks!
$endgroup$
– Kevin Cruijssen
Mar 25 at 14:25
1
$begingroup$
Actually, I think€Œ.«ÃéθJshould work for 8.
$endgroup$
– Adnan
Mar 25 at 19:58
1
1
$begingroup$
I think
€Œ.«Ãõªéθ should work for 9 bytes.$endgroup$
– Adnan
Mar 25 at 14:22
$begingroup$
I think
€Œ.«Ãõªéθ should work for 9 bytes.$endgroup$
– Adnan
Mar 25 at 14:22
$begingroup$
@Adnan Wait, we do have a reduce.. How did I miss that. :S I tried
Å«Ã, but didn't realize I should have used .«Ã instead.. Thanks!$endgroup$
– Kevin Cruijssen
Mar 25 at 14:25
$begingroup$
@Adnan Wait, we do have a reduce.. How did I miss that. :S I tried
Å«Ã, but didn't realize I should have used .«Ã instead.. Thanks!$endgroup$
– Kevin Cruijssen
Mar 25 at 14:25
1
1
$begingroup$
Actually, I think
€Œ.«ÃéθJ should work for 8.$endgroup$
– Adnan
Mar 25 at 19:58
$begingroup$
Actually, I think
€Œ.«ÃéθJ should work for 8.$endgroup$
– Adnan
Mar 25 at 19:58
add a comment |
$begingroup$
Zsh, 126 123 117 112 111 bytes
-3 bytes from arithmetic for, -6 bytes from implicit "$@" (thanks roblogic), -5 bytes from removing unneeded { }, -1 byte from short form of for
for l
{a= i=
for ((;i++<$#l**2;))a+=($l[1+i/$#l,1+i%$#l])
b=(${${b-$a}:*a})}
for s ($b)
(($#x<$#s))&&x=$s
<<<$x
Try it online!
We read all possible substrings into the arraya, and then set b to the intersection of the arrays a and b. The construct ${b-$a} will only substitue $a on the first iteration: Unlike its sibling expansion ${b:-$a}, it will not substitute when b is set but empty.
for l; { # implicit "$@"
a= i= # empty a and i
for (( ; i++ < $#l**2; )) # compound double loop using div/mod
a+=( $l[1+i/$#l,1+i%$#l] ) # append to a all possible substrings of the given line
# 1+i/$#l # 1,1,1..., 1,1,2,2,2,... ..., n,n
# 1+i%$#l # 1,2,3...,n-1,n,1,2,3,... ...,n-1,n
# a+=( $l[ , ] ) # append that substring to the array
b=( ${${b-$a}:*a} )
# ${b-$a} # if b is unset substitute $a
# ${ :*a} # take common elements of ${b-$a} and $a
# b=( ) # set b to those elements
}
for s ($b) # for every common substring
(( $#x < $#s )) && x=$s # if the current word is longer, use it
<<<$x # print to stdout
New contributor
GammaFunction is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
$begingroup$
How does this bit work?a+=( $l[1+i/$#l,1+i%$#l] )
$endgroup$
– roblogic
Mar 26 at 12:44
1
$begingroup$
@roblogic I think I explained it better now, check the edit. The idea is to loop to n^2 and use / and % instead of using 2 nestedforloops
$endgroup$
– GammaFunction
Mar 26 at 13:13
1
$begingroup$
you might be able to cutfor l in "$@"to simplyfor l;- it's a bash trick
$endgroup$
– roblogic
Mar 26 at 16:41
$begingroup$
i gotta say, zsh is so much more elegant than bash. There's nothing analogous to this nice array comparison AFAIKb=(${${b-$a}:*a})}
$endgroup$
– roblogic
2 days ago
1
$begingroup$
There's some neat things you can do with it, and it isn't all that popular. That translates into me adding a zsh answer to most questions I come across. :P If you want to learn zsh, I recommendman zshexpnandman zshparamespecially. I always have them open when writing an answer.
$endgroup$
– GammaFunction
2 days ago
add a comment |
$begingroup$
Zsh, 126 123 117 112 111 bytes
-3 bytes from arithmetic for, -6 bytes from implicit "$@" (thanks roblogic), -5 bytes from removing unneeded { }, -1 byte from short form of for
for l
{a= i=
for ((;i++<$#l**2;))a+=($l[1+i/$#l,1+i%$#l])
b=(${${b-$a}:*a})}
for s ($b)
(($#x<$#s))&&x=$s
<<<$x
Try it online!
We read all possible substrings into the arraya, and then set b to the intersection of the arrays a and b. The construct ${b-$a} will only substitue $a on the first iteration: Unlike its sibling expansion ${b:-$a}, it will not substitute when b is set but empty.
for l; { # implicit "$@"
a= i= # empty a and i
for (( ; i++ < $#l**2; )) # compound double loop using div/mod
a+=( $l[1+i/$#l,1+i%$#l] ) # append to a all possible substrings of the given line
# 1+i/$#l # 1,1,1..., 1,1,2,2,2,... ..., n,n
# 1+i%$#l # 1,2,3...,n-1,n,1,2,3,... ...,n-1,n
# a+=( $l[ , ] ) # append that substring to the array
b=( ${${b-$a}:*a} )
# ${b-$a} # if b is unset substitute $a
# ${ :*a} # take common elements of ${b-$a} and $a
# b=( ) # set b to those elements
}
for s ($b) # for every common substring
(( $#x < $#s )) && x=$s # if the current word is longer, use it
<<<$x # print to stdout
New contributor
GammaFunction is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
$begingroup$
How does this bit work?a+=( $l[1+i/$#l,1+i%$#l] )
$endgroup$
– roblogic
Mar 26 at 12:44
1
$begingroup$
@roblogic I think I explained it better now, check the edit. The idea is to loop to n^2 and use / and % instead of using 2 nestedforloops
$endgroup$
– GammaFunction
Mar 26 at 13:13
1
$begingroup$
you might be able to cutfor l in "$@"to simplyfor l;- it's a bash trick
$endgroup$
– roblogic
Mar 26 at 16:41
$begingroup$
i gotta say, zsh is so much more elegant than bash. There's nothing analogous to this nice array comparison AFAIKb=(${${b-$a}:*a})}
$endgroup$
– roblogic
2 days ago
1
$begingroup$
There's some neat things you can do with it, and it isn't all that popular. That translates into me adding a zsh answer to most questions I come across. :P If you want to learn zsh, I recommendman zshexpnandman zshparamespecially. I always have them open when writing an answer.
$endgroup$
– GammaFunction
2 days ago
add a comment |
$begingroup$
Zsh, 126 123 117 112 111 bytes
-3 bytes from arithmetic for, -6 bytes from implicit "$@" (thanks roblogic), -5 bytes from removing unneeded { }, -1 byte from short form of for
for l
{a= i=
for ((;i++<$#l**2;))a+=($l[1+i/$#l,1+i%$#l])
b=(${${b-$a}:*a})}
for s ($b)
(($#x<$#s))&&x=$s
<<<$x
Try it online!
We read all possible substrings into the arraya, and then set b to the intersection of the arrays a and b. The construct ${b-$a} will only substitue $a on the first iteration: Unlike its sibling expansion ${b:-$a}, it will not substitute when b is set but empty.
for l; { # implicit "$@"
a= i= # empty a and i
for (( ; i++ < $#l**2; )) # compound double loop using div/mod
a+=( $l[1+i/$#l,1+i%$#l] ) # append to a all possible substrings of the given line
# 1+i/$#l # 1,1,1..., 1,1,2,2,2,... ..., n,n
# 1+i%$#l # 1,2,3...,n-1,n,1,2,3,... ...,n-1,n
# a+=( $l[ , ] ) # append that substring to the array
b=( ${${b-$a}:*a} )
# ${b-$a} # if b is unset substitute $a
# ${ :*a} # take common elements of ${b-$a} and $a
# b=( ) # set b to those elements
}
for s ($b) # for every common substring
(( $#x < $#s )) && x=$s # if the current word is longer, use it
<<<$x # print to stdout
New contributor
GammaFunction is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
Zsh, 126 123 117 112 111 bytes
-3 bytes from arithmetic for, -6 bytes from implicit "$@" (thanks roblogic), -5 bytes from removing unneeded { }, -1 byte from short form of for
for l
{a= i=
for ((;i++<$#l**2;))a+=($l[1+i/$#l,1+i%$#l])
b=(${${b-$a}:*a})}
for s ($b)
(($#x<$#s))&&x=$s
<<<$x
Try it online!
We read all possible substrings into the arraya, and then set b to the intersection of the arrays a and b. The construct ${b-$a} will only substitue $a on the first iteration: Unlike its sibling expansion ${b:-$a}, it will not substitute when b is set but empty.
for l; { # implicit "$@"
a= i= # empty a and i
for (( ; i++ < $#l**2; )) # compound double loop using div/mod
a+=( $l[1+i/$#l,1+i%$#l] ) # append to a all possible substrings of the given line
# 1+i/$#l # 1,1,1..., 1,1,2,2,2,... ..., n,n
# 1+i%$#l # 1,2,3...,n-1,n,1,2,3,... ...,n-1,n
# a+=( $l[ , ] ) # append that substring to the array
b=( ${${b-$a}:*a} )
# ${b-$a} # if b is unset substitute $a
# ${ :*a} # take common elements of ${b-$a} and $a
# b=( ) # set b to those elements
}
for s ($b) # for every common substring
(( $#x < $#s )) && x=$s # if the current word is longer, use it
<<<$x # print to stdout
New contributor
GammaFunction is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
edited 2 days ago
New contributor
GammaFunction is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
answered Mar 25 at 2:55
GammaFunctionGammaFunction
2116
2116
New contributor
GammaFunction is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
GammaFunction is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
GammaFunction is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$begingroup$
How does this bit work?a+=( $l[1+i/$#l,1+i%$#l] )
$endgroup$
– roblogic
Mar 26 at 12:44
1
$begingroup$
@roblogic I think I explained it better now, check the edit. The idea is to loop to n^2 and use / and % instead of using 2 nestedforloops
$endgroup$
– GammaFunction
Mar 26 at 13:13
1
$begingroup$
you might be able to cutfor l in "$@"to simplyfor l;- it's a bash trick
$endgroup$
– roblogic
Mar 26 at 16:41
$begingroup$
i gotta say, zsh is so much more elegant than bash. There's nothing analogous to this nice array comparison AFAIKb=(${${b-$a}:*a})}
$endgroup$
– roblogic
2 days ago
1
$begingroup$
There's some neat things you can do with it, and it isn't all that popular. That translates into me adding a zsh answer to most questions I come across. :P If you want to learn zsh, I recommendman zshexpnandman zshparamespecially. I always have them open when writing an answer.
$endgroup$
– GammaFunction
2 days ago
add a comment |
$begingroup$
How does this bit work?a+=( $l[1+i/$#l,1+i%$#l] )
$endgroup$
– roblogic
Mar 26 at 12:44
1
$begingroup$
@roblogic I think I explained it better now, check the edit. The idea is to loop to n^2 and use / and % instead of using 2 nestedforloops
$endgroup$
– GammaFunction
Mar 26 at 13:13
1
$begingroup$
you might be able to cutfor l in "$@"to simplyfor l;- it's a bash trick
$endgroup$
– roblogic
Mar 26 at 16:41
$begingroup$
i gotta say, zsh is so much more elegant than bash. There's nothing analogous to this nice array comparison AFAIKb=(${${b-$a}:*a})}
$endgroup$
– roblogic
2 days ago
1
$begingroup$
There's some neat things you can do with it, and it isn't all that popular. That translates into me adding a zsh answer to most questions I come across. :P If you want to learn zsh, I recommendman zshexpnandman zshparamespecially. I always have them open when writing an answer.
$endgroup$
– GammaFunction
2 days ago
$begingroup$
How does this bit work?
a+=( $l[1+i/$#l,1+i%$#l] )$endgroup$
– roblogic
Mar 26 at 12:44
$begingroup$
How does this bit work?
a+=( $l[1+i/$#l,1+i%$#l] )$endgroup$
– roblogic
Mar 26 at 12:44
1
1
$begingroup$
@roblogic I think I explained it better now, check the edit. The idea is to loop to n^2 and use / and % instead of using 2 nested
for loops$endgroup$
– GammaFunction
Mar 26 at 13:13
$begingroup$
@roblogic I think I explained it better now, check the edit. The idea is to loop to n^2 and use / and % instead of using 2 nested
for loops$endgroup$
– GammaFunction
Mar 26 at 13:13
1
1
$begingroup$
you might be able to cut
for l in "$@" to simply for l; - it's a bash trick$endgroup$
– roblogic
Mar 26 at 16:41
$begingroup$
you might be able to cut
for l in "$@" to simply for l; - it's a bash trick$endgroup$
– roblogic
Mar 26 at 16:41
$begingroup$
i gotta say, zsh is so much more elegant than bash. There's nothing analogous to this nice array comparison AFAIK
b=(${${b-$a}:*a})}$endgroup$
– roblogic
2 days ago
$begingroup$
i gotta say, zsh is so much more elegant than bash. There's nothing analogous to this nice array comparison AFAIK
b=(${${b-$a}:*a})}$endgroup$
– roblogic
2 days ago
1
1
$begingroup$
There's some neat things you can do with it, and it isn't all that popular. That translates into me adding a zsh answer to most questions I come across. :P If you want to learn zsh, I recommend
man zshexpn and man zshparam especially. I always have them open when writing an answer.$endgroup$
– GammaFunction
2 days ago
$begingroup$
There's some neat things you can do with it, and it isn't all that popular. That translates into me adding a zsh answer to most questions I come across. :P If you want to learn zsh, I recommend
man zshexpn and man zshparam especially. I always have them open when writing an answer.$endgroup$
– GammaFunction
2 days ago
add a comment |
$begingroup$
Perl 6, 62 bytes
{~sort(-*.comb,keys [∩] .map(*.comb[^*X.. ^*+1]>>.join))[0]}
Try it online!
I'm a little annoyed the Perl 6 can't do set operations on lists of lists, which is why there's an extra .comb and >> in there. Another annoying thing is that max can't take an function for how to compare items, meaning I have to user sort instead.
$endgroup$
3
$begingroup$
maxcan take such a function (arity 1 though), either by position when called in OO mode, or a named:byargument in procedural mode.
$endgroup$
– Ven
Mar 25 at 9:31
add a comment |
$begingroup$
Perl 6, 62 bytes
{~sort(-*.comb,keys [∩] .map(*.comb[^*X.. ^*+1]>>.join))[0]}
Try it online!
I'm a little annoyed the Perl 6 can't do set operations on lists of lists, which is why there's an extra .comb and >> in there. Another annoying thing is that max can't take an function for how to compare items, meaning I have to user sort instead.
$endgroup$
3
$begingroup$
maxcan take such a function (arity 1 though), either by position when called in OO mode, or a named:byargument in procedural mode.
$endgroup$
– Ven
Mar 25 at 9:31
add a comment |
$begingroup$
Perl 6, 62 bytes
{~sort(-*.comb,keys [∩] .map(*.comb[^*X.. ^*+1]>>.join))[0]}
Try it online!
I'm a little annoyed the Perl 6 can't do set operations on lists of lists, which is why there's an extra .comb and >> in there. Another annoying thing is that max can't take an function for how to compare items, meaning I have to user sort instead.
$endgroup$
Perl 6, 62 bytes
{~sort(-*.comb,keys [∩] .map(*.comb[^*X.. ^*+1]>>.join))[0]}
Try it online!
I'm a little annoyed the Perl 6 can't do set operations on lists of lists, which is why there's an extra .comb and >> in there. Another annoying thing is that max can't take an function for how to compare items, meaning I have to user sort instead.
answered Mar 25 at 2:46
Jo KingJo King
25.7k363129
25.7k363129
3
$begingroup$
maxcan take such a function (arity 1 though), either by position when called in OO mode, or a named:byargument in procedural mode.
$endgroup$
– Ven
Mar 25 at 9:31
add a comment |
3
$begingroup$
maxcan take such a function (arity 1 though), either by position when called in OO mode, or a named:byargument in procedural mode.
$endgroup$
– Ven
Mar 25 at 9:31
3
3
$begingroup$
max can take such a function (arity 1 though), either by position when called in OO mode, or a named :by argument in procedural mode.$endgroup$
– Ven
Mar 25 at 9:31
$begingroup$
max can take such a function (arity 1 though), either by position when called in OO mode, or a named :by argument in procedural mode.$endgroup$
– Ven
Mar 25 at 9:31
add a comment |
$begingroup$
Haskell, 80 bytes
import Data.List
f(x:r)=last$sortOn(0<$)[s|s<-inits=<<tails x,all(isInfixOf s)r]
Try it online!
Get all suffixes (tails) of the first word x in the list and take all prefixes (inits) of those suffixes to get all substrings s of x. Keep each s that isInfixOf all strings in the remaining list r. Sort those substrings by length (using the (0<$) trick) and return the last.
$endgroup$
add a comment |
$begingroup$
Haskell, 80 bytes
import Data.List
f(x:r)=last$sortOn(0<$)[s|s<-inits=<<tails x,all(isInfixOf s)r]
Try it online!
Get all suffixes (tails) of the first word x in the list and take all prefixes (inits) of those suffixes to get all substrings s of x. Keep each s that isInfixOf all strings in the remaining list r. Sort those substrings by length (using the (0<$) trick) and return the last.
$endgroup$
add a comment |
$begingroup$
Haskell, 80 bytes
import Data.List
f(x:r)=last$sortOn(0<$)[s|s<-inits=<<tails x,all(isInfixOf s)r]
Try it online!
Get all suffixes (tails) of the first word x in the list and take all prefixes (inits) of those suffixes to get all substrings s of x. Keep each s that isInfixOf all strings in the remaining list r. Sort those substrings by length (using the (0<$) trick) and return the last.
$endgroup$
Haskell, 80 bytes
import Data.List
f(x:r)=last$sortOn(0<$)[s|s<-inits=<<tails x,all(isInfixOf s)r]
Try it online!
Get all suffixes (tails) of the first word x in the list and take all prefixes (inits) of those suffixes to get all substrings s of x. Keep each s that isInfixOf all strings in the remaining list r. Sort those substrings by length (using the (0<$) trick) and return the last.
edited Mar 25 at 8:08
answered Mar 25 at 7:59
LaikoniLaikoni
20.3k439103
20.3k439103
add a comment |
add a comment |
$begingroup$
TSQL query, 154 bytes
USE master
DECLARE @ table(a varchar(999)collate Latin1_General_CS_AI,i int identity)
INSERT @ values('string'),('stRIng');
SELECT top 1x FROM(SELECT
distinct substring(a,f.number,g.number)x,i
FROM spt_values f,spt_values g,@ WHERE'L'=g.type)D
GROUP BY x ORDER BY-sum(i),-len(x)
Try it online
Made case sensitive by declaring the column 'a' with collation containing CS (case sensitive).
Splitting all strings from 2540 starting positions(many identical) but the useful values range between 1 and 2070 and ending 0 to 22 characters after starting position, the end position could be longer by changing the type to 'P' instead of 'L', but would cripple performance.
These distinct strings within each rownumber are counted. The highest count will always be equal to the number of rows in the table variable '@'. Reversing the order on the same count will leave the substring with most matches on top of the results followed by reversed length of the substring will leave longest match with most matches on top. The query only select the top 1 row.
In order to get all answers, change the first part of the query to
SELECT top 1with ties x FROM
$endgroup$
add a comment |
$begingroup$
TSQL query, 154 bytes
USE master
DECLARE @ table(a varchar(999)collate Latin1_General_CS_AI,i int identity)
INSERT @ values('string'),('stRIng');
SELECT top 1x FROM(SELECT
distinct substring(a,f.number,g.number)x,i
FROM spt_values f,spt_values g,@ WHERE'L'=g.type)D
GROUP BY x ORDER BY-sum(i),-len(x)
Try it online
Made case sensitive by declaring the column 'a' with collation containing CS (case sensitive).
Splitting all strings from 2540 starting positions(many identical) but the useful values range between 1 and 2070 and ending 0 to 22 characters after starting position, the end position could be longer by changing the type to 'P' instead of 'L', but would cripple performance.
These distinct strings within each rownumber are counted. The highest count will always be equal to the number of rows in the table variable '@'. Reversing the order on the same count will leave the substring with most matches on top of the results followed by reversed length of the substring will leave longest match with most matches on top. The query only select the top 1 row.
In order to get all answers, change the first part of the query to
SELECT top 1with ties x FROM
$endgroup$
add a comment |
$begingroup$
TSQL query, 154 bytes
USE master
DECLARE @ table(a varchar(999)collate Latin1_General_CS_AI,i int identity)
INSERT @ values('string'),('stRIng');
SELECT top 1x FROM(SELECT
distinct substring(a,f.number,g.number)x,i
FROM spt_values f,spt_values g,@ WHERE'L'=g.type)D
GROUP BY x ORDER BY-sum(i),-len(x)
Try it online
Made case sensitive by declaring the column 'a' with collation containing CS (case sensitive).
Splitting all strings from 2540 starting positions(many identical) but the useful values range between 1 and 2070 and ending 0 to 22 characters after starting position, the end position could be longer by changing the type to 'P' instead of 'L', but would cripple performance.
These distinct strings within each rownumber are counted. The highest count will always be equal to the number of rows in the table variable '@'. Reversing the order on the same count will leave the substring with most matches on top of the results followed by reversed length of the substring will leave longest match with most matches on top. The query only select the top 1 row.
In order to get all answers, change the first part of the query to
SELECT top 1with ties x FROM
$endgroup$
TSQL query, 154 bytes
USE master
DECLARE @ table(a varchar(999)collate Latin1_General_CS_AI,i int identity)
INSERT @ values('string'),('stRIng');
SELECT top 1x FROM(SELECT
distinct substring(a,f.number,g.number)x,i
FROM spt_values f,spt_values g,@ WHERE'L'=g.type)D
GROUP BY x ORDER BY-sum(i),-len(x)
Try it online
Made case sensitive by declaring the column 'a' with collation containing CS (case sensitive).
Splitting all strings from 2540 starting positions(many identical) but the useful values range between 1 and 2070 and ending 0 to 22 characters after starting position, the end position could be longer by changing the type to 'P' instead of 'L', but would cripple performance.
These distinct strings within each rownumber are counted. The highest count will always be equal to the number of rows in the table variable '@'. Reversing the order on the same count will leave the substring with most matches on top of the results followed by reversed length of the substring will leave longest match with most matches on top. The query only select the top 1 row.
In order to get all answers, change the first part of the query to
SELECT top 1with ties x FROM
edited Mar 26 at 17:22
answered Mar 25 at 11:05
t-clausen.dkt-clausen.dk
2,044314
2,044314
add a comment |
add a comment |
$begingroup$
C# (Visual C# Interactive Compiler), 320 257 bytes
l=>(string.Join(",",l.Select(s=>new int[s.Length*s.Length*2].Select((i,j)=>string.Concat(s.Skip(j/-~s.Length).Take(j%-~s.Length))))
.Aggregate((a,b)=>a.Intersect(b)).GroupBy(x=>x.Length).OrderBy(x =>x.Key).LastOrDefault()?.Select(y=>y)??new List<string>()));
Try it online!
Props to @Expired Data and @dana
New contributor
Innat3 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
$begingroup$
You can just return the string from a function. So in Interactive compiler it might look something like this: 294 bytes
$endgroup$
– Expired Data
Mar 25 at 16:45
1
$begingroup$
Here's the solution golfed down some bytes 215 bytes
$endgroup$
– Expired Data
Mar 25 at 17:00
$begingroup$
@ExpiredData ah perfect this is the example I needed :)
$endgroup$
– Innat3
Mar 26 at 8:22
$begingroup$
186
$endgroup$
– dana
2 days ago
$begingroup$
184
$endgroup$
– Embodiment of Ignorance
2 days ago
add a comment |
$begingroup$
C# (Visual C# Interactive Compiler), 320 257 bytes
l=>(string.Join(",",l.Select(s=>new int[s.Length*s.Length*2].Select((i,j)=>string.Concat(s.Skip(j/-~s.Length).Take(j%-~s.Length))))
.Aggregate((a,b)=>a.Intersect(b)).GroupBy(x=>x.Length).OrderBy(x =>x.Key).LastOrDefault()?.Select(y=>y)??new List<string>()));
Try it online!
Props to @Expired Data and @dana
New contributor
Innat3 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
$begingroup$
You can just return the string from a function. So in Interactive compiler it might look something like this: 294 bytes
$endgroup$
– Expired Data
Mar 25 at 16:45
1
$begingroup$
Here's the solution golfed down some bytes 215 bytes
$endgroup$
– Expired Data
Mar 25 at 17:00
$begingroup$
@ExpiredData ah perfect this is the example I needed :)
$endgroup$
– Innat3
Mar 26 at 8:22
$begingroup$
186
$endgroup$
– dana
2 days ago
$begingroup$
184
$endgroup$
– Embodiment of Ignorance
2 days ago
add a comment |
$begingroup$
C# (Visual C# Interactive Compiler), 320 257 bytes
l=>(string.Join(",",l.Select(s=>new int[s.Length*s.Length*2].Select((i,j)=>string.Concat(s.Skip(j/-~s.Length).Take(j%-~s.Length))))
.Aggregate((a,b)=>a.Intersect(b)).GroupBy(x=>x.Length).OrderBy(x =>x.Key).LastOrDefault()?.Select(y=>y)??new List<string>()));
Try it online!
Props to @Expired Data and @dana
New contributor
Innat3 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
C# (Visual C# Interactive Compiler), 320 257 bytes
l=>(string.Join(",",l.Select(s=>new int[s.Length*s.Length*2].Select((i,j)=>string.Concat(s.Skip(j/-~s.Length).Take(j%-~s.Length))))
.Aggregate((a,b)=>a.Intersect(b)).GroupBy(x=>x.Length).OrderBy(x =>x.Key).LastOrDefault()?.Select(y=>y)??new List<string>()));
Try it online!
Props to @Expired Data and @dana
New contributor
Innat3 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
edited 2 days ago
New contributor
Innat3 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
answered Mar 25 at 11:33
Innat3Innat3
1514
1514
New contributor
Innat3 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Innat3 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Innat3 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$begingroup$
You can just return the string from a function. So in Interactive compiler it might look something like this: 294 bytes
$endgroup$
– Expired Data
Mar 25 at 16:45
1
$begingroup$
Here's the solution golfed down some bytes 215 bytes
$endgroup$
– Expired Data
Mar 25 at 17:00
$begingroup$
@ExpiredData ah perfect this is the example I needed :)
$endgroup$
– Innat3
Mar 26 at 8:22
$begingroup$
186
$endgroup$
– dana
2 days ago
$begingroup$
184
$endgroup$
– Embodiment of Ignorance
2 days ago
add a comment |
$begingroup$
You can just return the string from a function. So in Interactive compiler it might look something like this: 294 bytes
$endgroup$
– Expired Data
Mar 25 at 16:45
1
$begingroup$
Here's the solution golfed down some bytes 215 bytes
$endgroup$
– Expired Data
Mar 25 at 17:00
$begingroup$
@ExpiredData ah perfect this is the example I needed :)
$endgroup$
– Innat3
Mar 26 at 8:22
$begingroup$
186
$endgroup$
– dana
2 days ago
$begingroup$
184
$endgroup$
– Embodiment of Ignorance
2 days ago
$begingroup$
You can just return the string from a function. So in Interactive compiler it might look something like this: 294 bytes
$endgroup$
– Expired Data
Mar 25 at 16:45
$begingroup$
You can just return the string from a function. So in Interactive compiler it might look something like this: 294 bytes
$endgroup$
– Expired Data
Mar 25 at 16:45
1
1
$begingroup$
Here's the solution golfed down some bytes 215 bytes
$endgroup$
– Expired Data
Mar 25 at 17:00
$begingroup$
Here's the solution golfed down some bytes 215 bytes
$endgroup$
– Expired Data
Mar 25 at 17:00
$begingroup$
@ExpiredData ah perfect this is the example I needed :)
$endgroup$
– Innat3
Mar 26 at 8:22
$begingroup$
@ExpiredData ah perfect this is the example I needed :)
$endgroup$
– Innat3
Mar 26 at 8:22
$begingroup$
186
$endgroup$
– dana
2 days ago
$begingroup$
186
$endgroup$
– dana
2 days ago
$begingroup$
184
$endgroup$
– Embodiment of Ignorance
2 days ago
$begingroup$
184
$endgroup$
– Embodiment of Ignorance
2 days ago
add a comment |
$begingroup$
Japt -h, 8 bytes
(I could knock off the last 3 bytes and use the -Fh flag instead but I'm not a fan of using -F)
mã rf iP
Try it or run all test cases
mã rf iP :Implicit input of array
m :Map
ã : Substrings
r :Reduce by
f : Filter, keeping only elements that appear in both arrays
i :Prepend
P : An empty string
:Implicit output of last element
$endgroup$
add a comment |
$begingroup$
Japt -h, 8 bytes
(I could knock off the last 3 bytes and use the -Fh flag instead but I'm not a fan of using -F)
mã rf iP
Try it or run all test cases
mã rf iP :Implicit input of array
m :Map
ã : Substrings
r :Reduce by
f : Filter, keeping only elements that appear in both arrays
i :Prepend
P : An empty string
:Implicit output of last element
$endgroup$
add a comment |
$begingroup$
Japt -h, 8 bytes
(I could knock off the last 3 bytes and use the -Fh flag instead but I'm not a fan of using -F)
mã rf iP
Try it or run all test cases
mã rf iP :Implicit input of array
m :Map
ã : Substrings
r :Reduce by
f : Filter, keeping only elements that appear in both arrays
i :Prepend
P : An empty string
:Implicit output of last element
$endgroup$
Japt -h, 8 bytes
(I could knock off the last 3 bytes and use the -Fh flag instead but I'm not a fan of using -F)
mã rf iP
Try it or run all test cases
mã rf iP :Implicit input of array
m :Map
ã : Substrings
r :Reduce by
f : Filter, keeping only elements that appear in both arrays
i :Prepend
P : An empty string
:Implicit output of last element
edited Mar 25 at 11:47
answered Mar 25 at 9:22
ShaggyShaggy
19.1k21768
19.1k21768
add a comment |
add a comment |
$begingroup$
Japt v2.0a0 -hF, 8 bytes
Îã f@eøX
Thanks to Shaggy for saving 3 bytes
Try it
Îã //Generate all substrings of the first string
f@ //Filter; keep the substrings that satisfy the following predicate:
e // If all strings of the input...
øX // Contain this substring, then keep it
-h //Take last element
-F //If last element is undefined, default to empty string
$endgroup$
$begingroup$
You shouldn't need to sort by length at the end, saving 3 bytes. Also,-Fdefaults to the empty string.
$endgroup$
– Shaggy
Mar 25 at 11:49
add a comment |
$begingroup$
Japt v2.0a0 -hF, 8 bytes
Îã f@eøX
Thanks to Shaggy for saving 3 bytes
Try it
Îã //Generate all substrings of the first string
f@ //Filter; keep the substrings that satisfy the following predicate:
e // If all strings of the input...
øX // Contain this substring, then keep it
-h //Take last element
-F //If last element is undefined, default to empty string
$endgroup$
$begingroup$
You shouldn't need to sort by length at the end, saving 3 bytes. Also,-Fdefaults to the empty string.
$endgroup$
– Shaggy
Mar 25 at 11:49
add a comment |
$begingroup$
Japt v2.0a0 -hF, 8 bytes
Îã f@eøX
Thanks to Shaggy for saving 3 bytes
Try it
Îã //Generate all substrings of the first string
f@ //Filter; keep the substrings that satisfy the following predicate:
e // If all strings of the input...
øX // Contain this substring, then keep it
-h //Take last element
-F //If last element is undefined, default to empty string
$endgroup$
Japt v2.0a0 -hF, 8 bytes
Îã f@eøX
Thanks to Shaggy for saving 3 bytes
Try it
Îã //Generate all substrings of the first string
f@ //Filter; keep the substrings that satisfy the following predicate:
e // If all strings of the input...
øX // Contain this substring, then keep it
-h //Take last element
-F //If last element is undefined, default to empty string
edited Mar 25 at 18:52
answered Mar 25 at 2:49
Embodiment of IgnoranceEmbodiment of Ignorance
2,248126
2,248126
$begingroup$
You shouldn't need to sort by length at the end, saving 3 bytes. Also,-Fdefaults to the empty string.
$endgroup$
– Shaggy
Mar 25 at 11:49
add a comment |
$begingroup$
You shouldn't need to sort by length at the end, saving 3 bytes. Also,-Fdefaults to the empty string.
$endgroup$
– Shaggy
Mar 25 at 11:49
$begingroup$
You shouldn't need to sort by length at the end, saving 3 bytes. Also,
-F defaults to the empty string.$endgroup$
– Shaggy
Mar 25 at 11:49
$begingroup$
You shouldn't need to sort by length at the end, saving 3 bytes. Also,
-F defaults to the empty string.$endgroup$
– Shaggy
Mar 25 at 11:49
add a comment |
$begingroup$
Retina 0.8.2, 48 bytes
M&!`(?<=^.*)(.+)(?=(.*n.*1)*.*$)
O#$^`
$.&
1G`
Try it online! Explanation:
M&!`(?<=^.*)(.+)(?=(.*n.*1)*.*$)
For each suffix of the first string, find the longest prefix that's also a substring of all of the other strings. List all of those suffix prefixes (i.e. substrings). If there are no matching substrings, we just end up with the empty string, which is what we want anyway.
O#$^`
$.&
Sort the substrings in reverse order of length.
1G`
Keep only the first, i.e. the longest substring.
$endgroup$
$begingroup$
Letnis number of argument strings. Then(?=(.*n.*1)*.*$)should be(?=(.*n.*1){n-1}.*$), isn't it? Test case:["very", "different", "much"] -> [""]
$endgroup$
– mazzy
2 days ago
1
$begingroup$
@mazzy I don't see the problem: Try it online!
$endgroup$
– Neil
2 days ago
$begingroup$
it is not a problem. with{n}you could remove start and end patterns and keep(.+)(?=(.*n.*1){n}if Retina allows to writenshorter than(?<=^.*).*$
$endgroup$
– mazzy
2 days ago
$begingroup$
@mazzy I can't in Retina 0.8.2, and in Retina 1 I'd have to mess around with eval, which would probably be longer anyway.
$endgroup$
– Neil
2 days ago
add a comment |
$begingroup$
Retina 0.8.2, 48 bytes
M&!`(?<=^.*)(.+)(?=(.*n.*1)*.*$)
O#$^`
$.&
1G`
Try it online! Explanation:
M&!`(?<=^.*)(.+)(?=(.*n.*1)*.*$)
For each suffix of the first string, find the longest prefix that's also a substring of all of the other strings. List all of those suffix prefixes (i.e. substrings). If there are no matching substrings, we just end up with the empty string, which is what we want anyway.
O#$^`
$.&
Sort the substrings in reverse order of length.
1G`
Keep only the first, i.e. the longest substring.
$endgroup$
$begingroup$
Letnis number of argument strings. Then(?=(.*n.*1)*.*$)should be(?=(.*n.*1){n-1}.*$), isn't it? Test case:["very", "different", "much"] -> [""]
$endgroup$
– mazzy
2 days ago
1
$begingroup$
@mazzy I don't see the problem: Try it online!
$endgroup$
– Neil
2 days ago
$begingroup$
it is not a problem. with{n}you could remove start and end patterns and keep(.+)(?=(.*n.*1){n}if Retina allows to writenshorter than(?<=^.*).*$
$endgroup$
– mazzy
2 days ago
$begingroup$
@mazzy I can't in Retina 0.8.2, and in Retina 1 I'd have to mess around with eval, which would probably be longer anyway.
$endgroup$
– Neil
2 days ago
add a comment |
$begingroup$
Retina 0.8.2, 48 bytes
M&!`(?<=^.*)(.+)(?=(.*n.*1)*.*$)
O#$^`
$.&
1G`
Try it online! Explanation:
M&!`(?<=^.*)(.+)(?=(.*n.*1)*.*$)
For each suffix of the first string, find the longest prefix that's also a substring of all of the other strings. List all of those suffix prefixes (i.e. substrings). If there are no matching substrings, we just end up with the empty string, which is what we want anyway.
O#$^`
$.&
Sort the substrings in reverse order of length.
1G`
Keep only the first, i.e. the longest substring.
$endgroup$
Retina 0.8.2, 48 bytes
M&!`(?<=^.*)(.+)(?=(.*n.*1)*.*$)
O#$^`
$.&
1G`
Try it online! Explanation:
M&!`(?<=^.*)(.+)(?=(.*n.*1)*.*$)
For each suffix of the first string, find the longest prefix that's also a substring of all of the other strings. List all of those suffix prefixes (i.e. substrings). If there are no matching substrings, we just end up with the empty string, which is what we want anyway.
O#$^`
$.&
Sort the substrings in reverse order of length.
1G`
Keep only the first, i.e. the longest substring.
edited Mar 26 at 0:51
answered Mar 26 at 0:28
NeilNeil
82.1k745178
82.1k745178
$begingroup$
Letnis number of argument strings. Then(?=(.*n.*1)*.*$)should be(?=(.*n.*1){n-1}.*$), isn't it? Test case:["very", "different", "much"] -> [""]
$endgroup$
– mazzy
2 days ago
1
$begingroup$
@mazzy I don't see the problem: Try it online!
$endgroup$
– Neil
2 days ago
$begingroup$
it is not a problem. with{n}you could remove start and end patterns and keep(.+)(?=(.*n.*1){n}if Retina allows to writenshorter than(?<=^.*).*$
$endgroup$
– mazzy
2 days ago
$begingroup$
@mazzy I can't in Retina 0.8.2, and in Retina 1 I'd have to mess around with eval, which would probably be longer anyway.
$endgroup$
– Neil
2 days ago
add a comment |
$begingroup$
Letnis number of argument strings. Then(?=(.*n.*1)*.*$)should be(?=(.*n.*1){n-1}.*$), isn't it? Test case:["very", "different", "much"] -> [""]
$endgroup$
– mazzy
2 days ago
1
$begingroup$
@mazzy I don't see the problem: Try it online!
$endgroup$
– Neil
2 days ago
$begingroup$
it is not a problem. with{n}you could remove start and end patterns and keep(.+)(?=(.*n.*1){n}if Retina allows to writenshorter than(?<=^.*).*$
$endgroup$
– mazzy
2 days ago
$begingroup$
@mazzy I can't in Retina 0.8.2, and in Retina 1 I'd have to mess around with eval, which would probably be longer anyway.
$endgroup$
– Neil
2 days ago
$begingroup$
Let
n is number of argument strings. Then (?=(.*n.*1)*.*$) should be (?=(.*n.*1){n-1}.*$), isn't it? Test case: ["very", "different", "much"] -> [""]$endgroup$
– mazzy
2 days ago
$begingroup$
Let
n is number of argument strings. Then (?=(.*n.*1)*.*$) should be (?=(.*n.*1){n-1}.*$), isn't it? Test case: ["very", "different", "much"] -> [""]$endgroup$
– mazzy
2 days ago
1
1
$begingroup$
@mazzy I don't see the problem: Try it online!
$endgroup$
– Neil
2 days ago
$begingroup$
@mazzy I don't see the problem: Try it online!
$endgroup$
– Neil
2 days ago
$begingroup$
it is not a problem. with
{n} you could remove start and end patterns and keep (.+)(?=(.*n.*1){n} if Retina allows to write n shorter than (?<=^.*).*$$endgroup$
– mazzy
2 days ago
$begingroup$
it is not a problem. with
{n} you could remove start and end patterns and keep (.+)(?=(.*n.*1){n} if Retina allows to write n shorter than (?<=^.*).*$$endgroup$
– mazzy
2 days ago
$begingroup$
@mazzy I can't in Retina 0.8.2, and in Retina 1 I'd have to mess around with eval, which would probably be longer anyway.
$endgroup$
– Neil
2 days ago
$begingroup$
@mazzy I can't in Retina 0.8.2, and in Retina 1 I'd have to mess around with eval, which would probably be longer anyway.
$endgroup$
– Neil
2 days ago
add a comment |
$begingroup$
Python 3, 137 bytes
def a(b):c=[[d[f:e]for e in range(len(d)+1)for f in range(e+1)]for d in b];return max([i for i in c[0]if all(i in j for j in c)],key=len)
Try it online!
New contributor
Artemis Fowl is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
$begingroup$
You may want to use single spaces as indentation instead of 4 that seems to shave more than 100 bytes.
$endgroup$
– Shieru Asakoto
Mar 25 at 1:21
$begingroup$
@JoKing tio.run/…
$endgroup$
– Artemis Fowl
Mar 25 at 2:20
$begingroup$
Right, here's a fixed version of the 135 byte program
$endgroup$
– Jo King
Mar 25 at 2:29
add a comment |
$begingroup$
Python 3, 137 bytes
def a(b):c=[[d[f:e]for e in range(len(d)+1)for f in range(e+1)]for d in b];return max([i for i in c[0]if all(i in j for j in c)],key=len)
Try it online!
New contributor
Artemis Fowl is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
$begingroup$
You may want to use single spaces as indentation instead of 4 that seems to shave more than 100 bytes.
$endgroup$
– Shieru Asakoto
Mar 25 at 1:21
$begingroup$
@JoKing tio.run/…
$endgroup$
– Artemis Fowl
Mar 25 at 2:20
$begingroup$
Right, here's a fixed version of the 135 byte program
$endgroup$
– Jo King
Mar 25 at 2:29
add a comment |
$begingroup$
Python 3, 137 bytes
def a(b):c=[[d[f:e]for e in range(len(d)+1)for f in range(e+1)]for d in b];return max([i for i in c[0]if all(i in j for j in c)],key=len)
Try it online!
New contributor
Artemis Fowl is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
Python 3, 137 bytes
def a(b):c=[[d[f:e]for e in range(len(d)+1)for f in range(e+1)]for d in b];return max([i for i in c[0]if all(i in j for j in c)],key=len)
Try it online!
New contributor
Artemis Fowl is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
edited Mar 25 at 2:29
New contributor
Artemis Fowl is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
answered Mar 25 at 1:17
Artemis FowlArtemis Fowl
1114
1114
New contributor
Artemis Fowl is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Artemis Fowl is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Artemis Fowl is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$begingroup$
You may want to use single spaces as indentation instead of 4 that seems to shave more than 100 bytes.
$endgroup$
– Shieru Asakoto
Mar 25 at 1:21
$begingroup$
@JoKing tio.run/…
$endgroup$
– Artemis Fowl
Mar 25 at 2:20
$begingroup$
Right, here's a fixed version of the 135 byte program
$endgroup$
– Jo King
Mar 25 at 2:29
add a comment |
$begingroup$
You may want to use single spaces as indentation instead of 4 that seems to shave more than 100 bytes.
$endgroup$
– Shieru Asakoto
Mar 25 at 1:21
$begingroup$
@JoKing tio.run/…
$endgroup$
– Artemis Fowl
Mar 25 at 2:20
$begingroup$
Right, here's a fixed version of the 135 byte program
$endgroup$
– Jo King
Mar 25 at 2:29
$begingroup$
You may want to use single spaces as indentation instead of 4 that seems to shave more than 100 bytes.
$endgroup$
– Shieru Asakoto
Mar 25 at 1:21
$begingroup$
You may want to use single spaces as indentation instead of 4 that seems to shave more than 100 bytes.
$endgroup$
– Shieru Asakoto
Mar 25 at 1:21
$begingroup$
@JoKing tio.run/…
$endgroup$
– Artemis Fowl
Mar 25 at 2:20
$begingroup$
@JoKing tio.run/…
$endgroup$
– Artemis Fowl
Mar 25 at 2:20
$begingroup$
Right, here's a fixed version of the 135 byte program
$endgroup$
– Jo King
Mar 25 at 2:29
$begingroup$
Right, here's a fixed version of the 135 byte program
$endgroup$
– Jo King
Mar 25 at 2:29
add a comment |
$begingroup$
Python 2, 103 bytes
lambda b:max(reduce(set.__and__,[{d[f:e]for e in range(len(d)+2)for f in range(e)}for d in b]),key=len)
Try it online!
This is an anonymous lambda that transforms each element into the set of all substrings, then reduces it by set intersection (set.__and__) and then returns the max element by length.
$endgroup$
$begingroup$
1 byte shorter withset.intersection.
$endgroup$
– ovs
Mar 25 at 11:45
add a comment |
$begingroup$
Python 2, 103 bytes
lambda b:max(reduce(set.__and__,[{d[f:e]for e in range(len(d)+2)for f in range(e)}for d in b]),key=len)
Try it online!
This is an anonymous lambda that transforms each element into the set of all substrings, then reduces it by set intersection (set.__and__) and then returns the max element by length.
$endgroup$
$begingroup$
1 byte shorter withset.intersection.
$endgroup$
– ovs
Mar 25 at 11:45
add a comment |
$begingroup$
Python 2, 103 bytes
lambda b:max(reduce(set.__and__,[{d[f:e]for e in range(len(d)+2)for f in range(e)}for d in b]),key=len)
Try it online!
This is an anonymous lambda that transforms each element into the set of all substrings, then reduces it by set intersection (set.__and__) and then returns the max element by length.
$endgroup$
Python 2, 103 bytes
lambda b:max(reduce(set.__and__,[{d[f:e]for e in range(len(d)+2)for f in range(e)}for d in b]),key=len)
Try it online!
This is an anonymous lambda that transforms each element into the set of all substrings, then reduces it by set intersection (set.__and__) and then returns the max element by length.
edited Mar 25 at 3:08
answered Mar 25 at 2:57
Jo KingJo King
25.7k363129
25.7k363129
$begingroup$
1 byte shorter withset.intersection.
$endgroup$
– ovs
Mar 25 at 11:45
add a comment |
$begingroup$
1 byte shorter withset.intersection.
$endgroup$
– ovs
Mar 25 at 11:45
$begingroup$
1 byte shorter with
set.intersection.$endgroup$
– ovs
Mar 25 at 11:45
$begingroup$
1 byte shorter with
set.intersection.$endgroup$
– ovs
Mar 25 at 11:45
add a comment |
$begingroup$
C# (Visual C# Interactive Compiler), 147 145 bytes
a=>{int i=0,j,m=0,k=a[0].Length;string s="",d=s;for(;i<k;i++)for(j=m;j++<k-i;)if(a.All(y=>y.Contains(s=a[0].Substring(i,j)))){m=j;d=s;}return d;}
Try it online!
$endgroup$
add a comment |
$begingroup$
C# (Visual C# Interactive Compiler), 147 145 bytes
a=>{int i=0,j,m=0,k=a[0].Length;string s="",d=s;for(;i<k;i++)for(j=m;j++<k-i;)if(a.All(y=>y.Contains(s=a[0].Substring(i,j)))){m=j;d=s;}return d;}
Try it online!
$endgroup$
add a comment |
$begingroup$
C# (Visual C# Interactive Compiler), 147 145 bytes
a=>{int i=0,j,m=0,k=a[0].Length;string s="",d=s;for(;i<k;i++)for(j=m;j++<k-i;)if(a.All(y=>y.Contains(s=a[0].Substring(i,j)))){m=j;d=s;}return d;}
Try it online!
$endgroup$
C# (Visual C# Interactive Compiler), 147 145 bytes
a=>{int i=0,j,m=0,k=a[0].Length;string s="",d=s;for(;i<k;i++)for(j=m;j++<k-i;)if(a.All(y=>y.Contains(s=a[0].Substring(i,j)))){m=j;d=s;}return d;}
Try it online!
edited Mar 25 at 15:15
answered Mar 25 at 14:57
Expired DataExpired Data
4188
4188
add a comment |
add a comment |
$begingroup$
Perl 5 (-aln0777F/n/ -M5.01 -MList::util=max), 99 bytes
may be golfed more certainly
map/(.+)(?!.*1)(?{$h{$&}++})(?!)/,@F;say for grep{y///c==max map y///c,@b}@b=grep@F==$h{$_},keys%h
TIO
$endgroup$
add a comment |
$begingroup$
Perl 5 (-aln0777F/n/ -M5.01 -MList::util=max), 99 bytes
may be golfed more certainly
map/(.+)(?!.*1)(?{$h{$&}++})(?!)/,@F;say for grep{y///c==max map y///c,@b}@b=grep@F==$h{$_},keys%h
TIO
$endgroup$
add a comment |
$begingroup$
Perl 5 (-aln0777F/n/ -M5.01 -MList::util=max), 99 bytes
may be golfed more certainly
map/(.+)(?!.*1)(?{$h{$&}++})(?!)/,@F;say for grep{y///c==max map y///c,@b}@b=grep@F==$h{$_},keys%h
TIO
$endgroup$
Perl 5 (-aln0777F/n/ -M5.01 -MList::util=max), 99 bytes
may be golfed more certainly
map/(.+)(?!.*1)(?{$h{$&}++})(?!)/,@F;say for grep{y///c==max map y///c,@b}@b=grep@F==$h{$_},keys%h
TIO
edited Mar 25 at 16:35
answered Mar 25 at 16:27
Nahuel FouilleulNahuel Fouilleul
2,925211
2,925211
add a comment |
add a comment |
$begingroup$
JavaScript (ES6), 98 92 bytes
a=>(g=b=s=>a.every(x=>~x.indexOf(s))?b=b[s.length]?b:s:g(s.slice(0,-1,g(s.slice(1)))))(a[0])
Try it online!
$endgroup$
add a comment |
$begingroup$
JavaScript (ES6), 98 92 bytes
a=>(g=b=s=>a.every(x=>~x.indexOf(s))?b=b[s.length]?b:s:g(s.slice(0,-1,g(s.slice(1)))))(a[0])
Try it online!
$endgroup$
add a comment |
$begingroup$
JavaScript (ES6), 98 92 bytes
a=>(g=b=s=>a.every(x=>~x.indexOf(s))?b=b[s.length]?b:s:g(s.slice(0,-1,g(s.slice(1)))))(a[0])
Try it online!
$endgroup$
JavaScript (ES6), 98 92 bytes
a=>(g=b=s=>a.every(x=>~x.indexOf(s))?b=b[s.length]?b:s:g(s.slice(0,-1,g(s.slice(1)))))(a[0])
Try it online!
edited Mar 25 at 17:38
answered Mar 25 at 15:10
ArnauldArnauld
79.9k797330
79.9k797330
add a comment |
add a comment |
$begingroup$
Bash 4+, 295... 178 bytes
Not pretty but at least it works.
Try it Online
-37 by general cleaning up ;
-52 by plagiarising from the zsh answer ;
-26 by replacing array with a loop ;
-2 thanks to GammaFunction
for l;{ d=${#l}
for((i=0;i<d**2;i++)){ a="${l:i/d:1+i%d}" k=
for n;{ [[ $n =~ $a ]]&&((k++));}
((k-$#))||b+=("$a");};}
for e in "${b[@]}";do((${#e}>${#f}))&&f="$e";done
echo "$f"
Here's the original ungolfed script with comments
New contributor
roblogic is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
1
$begingroup$
Save 2 more: You can replace((k==$#))&&with((k-$#))||. This also lets you usek=instead of setting it to 0.
$endgroup$
– GammaFunction
2 days ago
1
$begingroup$
I think "Not pretty but at least it works" is the MO for bash scripts :)
$endgroup$
– joeytwiddle
2 days ago
add a comment |
$begingroup$
Bash 4+, 295... 178 bytes
Not pretty but at least it works.
Try it Online
-37 by general cleaning up ;
-52 by plagiarising from the zsh answer ;
-26 by replacing array with a loop ;
-2 thanks to GammaFunction
for l;{ d=${#l}
for((i=0;i<d**2;i++)){ a="${l:i/d:1+i%d}" k=
for n;{ [[ $n =~ $a ]]&&((k++));}
((k-$#))||b+=("$a");};}
for e in "${b[@]}";do((${#e}>${#f}))&&f="$e";done
echo "$f"
Here's the original ungolfed script with comments
New contributor
roblogic is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
1
$begingroup$
Save 2 more: You can replace((k==$#))&&with((k-$#))||. This also lets you usek=instead of setting it to 0.
$endgroup$
– GammaFunction
2 days ago
1
$begingroup$
I think "Not pretty but at least it works" is the MO for bash scripts :)
$endgroup$
– joeytwiddle
2 days ago
add a comment |
$begingroup$
Bash 4+, 295... 178 bytes
Not pretty but at least it works.
Try it Online
-37 by general cleaning up ;
-52 by plagiarising from the zsh answer ;
-26 by replacing array with a loop ;
-2 thanks to GammaFunction
for l;{ d=${#l}
for((i=0;i<d**2;i++)){ a="${l:i/d:1+i%d}" k=
for n;{ [[ $n =~ $a ]]&&((k++));}
((k-$#))||b+=("$a");};}
for e in "${b[@]}";do((${#e}>${#f}))&&f="$e";done
echo "$f"
Here's the original ungolfed script with comments
New contributor
roblogic is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
Bash 4+, 295... 178 bytes
Not pretty but at least it works.
Try it Online
-37 by general cleaning up ;
-52 by plagiarising from the zsh answer ;
-26 by replacing array with a loop ;
-2 thanks to GammaFunction
for l;{ d=${#l}
for((i=0;i<d**2;i++)){ a="${l:i/d:1+i%d}" k=
for n;{ [[ $n =~ $a ]]&&((k++));}
((k-$#))||b+=("$a");};}
for e in "${b[@]}";do((${#e}>${#f}))&&f="$e";done
echo "$f"
Here's the original ungolfed script with comments
New contributor
roblogic is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
edited 2 days ago
New contributor
roblogic is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
answered Mar 26 at 15:59
roblogicroblogic
1515
1515
New contributor
roblogic is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
roblogic is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
roblogic is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
$begingroup$
Save 2 more: You can replace((k==$#))&&with((k-$#))||. This also lets you usek=instead of setting it to 0.
$endgroup$
– GammaFunction
2 days ago
1
$begingroup$
I think "Not pretty but at least it works" is the MO for bash scripts :)
$endgroup$
– joeytwiddle
2 days ago
add a comment |
1
$begingroup$
Save 2 more: You can replace((k==$#))&&with((k-$#))||. This also lets you usek=instead of setting it to 0.
$endgroup$
– GammaFunction
2 days ago
1
$begingroup$
I think "Not pretty but at least it works" is the MO for bash scripts :)
$endgroup$
– joeytwiddle
2 days ago
1
1
$begingroup$
Save 2 more: You can replace
((k==$#))&& with ((k-$#))||. This also lets you use k= instead of setting it to 0.$endgroup$
– GammaFunction
2 days ago
$begingroup$
Save 2 more: You can replace
((k==$#))&& with ((k-$#))||. This also lets you use k= instead of setting it to 0.$endgroup$
– GammaFunction
2 days ago
1
1
$begingroup$
I think "Not pretty but at least it works" is the MO for bash scripts :)
$endgroup$
– joeytwiddle
2 days ago
$begingroup$
I think "Not pretty but at least it works" is the MO for bash scripts :)
$endgroup$
– joeytwiddle
2 days ago
add a comment |
$begingroup$
Java (JDK), 176 bytes
a->{int l=a.get(0).length(),m=0,i=0,j;var r="";for(;i<l;i++)for(j=i;j++<l;){var s=a.get(0).substring(i,j);if(j-i>m&a.stream().allMatch(x->x.contains(s))){r=s;m=j-i;}}return r;}
Try it online!
This is a rather naive implementation.
$endgroup$
add a comment |
$begingroup$
Java (JDK), 176 bytes
a->{int l=a.get(0).length(),m=0,i=0,j;var r="";for(;i<l;i++)for(j=i;j++<l;){var s=a.get(0).substring(i,j);if(j-i>m&a.stream().allMatch(x->x.contains(s))){r=s;m=j-i;}}return r;}
Try it online!
This is a rather naive implementation.
$endgroup$
add a comment |
$begingroup$
Java (JDK), 176 bytes
a->{int l=a.get(0).length(),m=0,i=0,j;var r="";for(;i<l;i++)for(j=i;j++<l;){var s=a.get(0).substring(i,j);if(j-i>m&a.stream().allMatch(x->x.contains(s))){r=s;m=j-i;}}return r;}
Try it online!
This is a rather naive implementation.
$endgroup$
Java (JDK), 176 bytes
a->{int l=a.get(0).length(),m=0,i=0,j;var r="";for(;i<l;i++)for(j=i;j++<l;){var s=a.get(0).substring(i,j);if(j-i>m&a.stream().allMatch(x->x.contains(s))){r=s;m=j-i;}}return r;}
Try it online!
This is a rather naive implementation.
answered Mar 25 at 9:41
Olivier GrégoireOlivier Grégoire
9,33511944
9,33511944
add a comment |
add a comment |
$begingroup$
Red, 266 174 bytes
func[b][l: length? s: b/1 n: 1 until[i: 1 loop n[t: copy/part at s i l r: on foreach u
next b[r: r and(none <> find/case u t)]if r[return t]i: i + 1]n: n + 1 1 > l: l - 1]""]
Try it online!
Changed the recursion to iteration and got rid of the sorting.
$endgroup$
add a comment |
$begingroup$
Red, 266 174 bytes
func[b][l: length? s: b/1 n: 1 until[i: 1 loop n[t: copy/part at s i l r: on foreach u
next b[r: r and(none <> find/case u t)]if r[return t]i: i + 1]n: n + 1 1 > l: l - 1]""]
Try it online!
Changed the recursion to iteration and got rid of the sorting.
$endgroup$
add a comment |
$begingroup$
Red, 266 174 bytes
func[b][l: length? s: b/1 n: 1 until[i: 1 loop n[t: copy/part at s i l r: on foreach u
next b[r: r and(none <> find/case u t)]if r[return t]i: i + 1]n: n + 1 1 > l: l - 1]""]
Try it online!
Changed the recursion to iteration and got rid of the sorting.
$endgroup$
Red, 266 174 bytes
func[b][l: length? s: b/1 n: 1 until[i: 1 loop n[t: copy/part at s i l r: on foreach u
next b[r: r and(none <> find/case u t)]if r[return t]i: i + 1]n: n + 1 1 > l: l - 1]""]
Try it online!
Changed the recursion to iteration and got rid of the sorting.
edited Mar 25 at 19:05
answered Mar 25 at 12:02
Galen IvanovGalen Ivanov
7,34211034
7,34211034
add a comment |
add a comment |
$begingroup$
Perl 5, 87 bytes
my$r;"$&@_"=~/(.{@{[$r=~y,,,c]},}).*(n.*1.*){@{[@_-1]}}/ and$r=$1while$_[0]=~s,.,,;$r
Try it online!
$endgroup$
add a comment |
$begingroup$
Perl 5, 87 bytes
my$r;"$&@_"=~/(.{@{[$r=~y,,,c]},}).*(n.*1.*){@{[@_-1]}}/ and$r=$1while$_[0]=~s,.,,;$r
Try it online!
$endgroup$
add a comment |
$begingroup$
Perl 5, 87 bytes
my$r;"$&@_"=~/(.{@{[$r=~y,,,c]},}).*(n.*1.*){@{[@_-1]}}/ and$r=$1while$_[0]=~s,.,,;$r
Try it online!
$endgroup$
Perl 5, 87 bytes
my$r;"$&@_"=~/(.{@{[$r=~y,,,c]},}).*(n.*1.*){@{[@_-1]}}/ and$r=$1while$_[0]=~s,.,,;$r
Try it online!
answered Mar 25 at 22:18
Kjetil S.Kjetil S.
58925
58925
add a comment |
add a comment |
$begingroup$
JavaScript (Node.js), 106 bytes
a=>(F=(l,n,w=a[0].substr(n,l))=>l?n<0?F(--l,L-l):a.some(y=>y.indexOf(w)<0)?F(l,n-1):w:"")(L=a[0].length,0)
Try it online!
a=>( // Main function
F=( // Helper function to run through all substrings in a[0]
l, // Length
n, // Start position
w=a[0].substr(n,l) // The substring
)=>
l? // If l > 0:
n<0? // If n < 0:
F(--l,L-l) // Check another length
:a.some( // If n >= 0:
y=>y.indexOf(w)<0 // Check whether there is any string not containing the substring
// (indexOf used because of presence of regex special characters)
)? // If so:
F(l,n-1) // Check another substring
:w // If not, return this substring and terminate
// (This function checks from the longest substring possible, so
// it is safe to return right here)
:"" // If l <= 0: Return empty string (no common substring)
)(
L=a[0].length, // Starts from length = the whole length of a[0]
0 // And start position = 0
)
$endgroup$
add a comment |
$begingroup$
JavaScript (Node.js), 106 bytes
a=>(F=(l,n,w=a[0].substr(n,l))=>l?n<0?F(--l,L-l):a.some(y=>y.indexOf(w)<0)?F(l,n-1):w:"")(L=a[0].length,0)
Try it online!
a=>( // Main function
F=( // Helper function to run through all substrings in a[0]
l, // Length
n, // Start position
w=a[0].substr(n,l) // The substring
)=>
l? // If l > 0:
n<0? // If n < 0:
F(--l,L-l) // Check another length
:a.some( // If n >= 0:
y=>y.indexOf(w)<0 // Check whether there is any string not containing the substring
// (indexOf used because of presence of regex special characters)
)? // If so:
F(l,n-1) // Check another substring
:w // If not, return this substring and terminate
// (This function checks from the longest substring possible, so
// it is safe to return right here)
:"" // If l <= 0: Return empty string (no common substring)
)(
L=a[0].length, // Starts from length = the whole length of a[0]
0 // And start position = 0
)
$endgroup$
add a comment |
$begingroup$
JavaScript (Node.js), 106 bytes
a=>(F=(l,n,w=a[0].substr(n,l))=>l?n<0?F(--l,L-l):a.some(y=>y.indexOf(w)<0)?F(l,n-1):w:"")(L=a[0].length,0)
Try it online!
a=>( // Main function
F=( // Helper function to run through all substrings in a[0]
l, // Length
n, // Start position
w=a[0].substr(n,l) // The substring
)=>
l? // If l > 0:
n<0? // If n < 0:
F(--l,L-l) // Check another length
:a.some( // If n >= 0:
y=>y.indexOf(w)<0 // Check whether there is any string not containing the substring
// (indexOf used because of presence of regex special characters)
)? // If so:
F(l,n-1) // Check another substring
:w // If not, return this substring and terminate
// (This function checks from the longest substring possible, so
// it is safe to return right here)
:"" // If l <= 0: Return empty string (no common substring)
)(
L=a[0].length, // Starts from length = the whole length of a[0]
0 // And start position = 0
)
$endgroup$
JavaScript (Node.js), 106 bytes
a=>(F=(l,n,w=a[0].substr(n,l))=>l?n<0?F(--l,L-l):a.some(y=>y.indexOf(w)<0)?F(l,n-1):w:"")(L=a[0].length,0)
Try it online!
a=>( // Main function
F=( // Helper function to run through all substrings in a[0]
l, // Length
n, // Start position
w=a[0].substr(n,l) // The substring
)=>
l? // If l > 0:
n<0? // If n < 0:
F(--l,L-l) // Check another length
:a.some( // If n >= 0:
y=>y.indexOf(w)<0 // Check whether there is any string not containing the substring
// (indexOf used because of presence of regex special characters)
)? // If so:
F(l,n-1) // Check another substring
:w // If not, return this substring and terminate
// (This function checks from the longest substring possible, so
// it is safe to return right here)
:"" // If l <= 0: Return empty string (no common substring)
)(
L=a[0].length, // Starts from length = the whole length of a[0]
0 // And start position = 0
)
edited Mar 26 at 1:12
answered Mar 25 at 1:48
Shieru AsakotoShieru Asakoto
2,750317
2,750317
add a comment |
add a comment |
$begingroup$
Gaia, 15 bytes
eḋ¦&⊢⟨:l¦:⌉=¦⟩∇
Try it online!
e | eval as code
ḋ¦ | find all non-empty substrings
&⊢ | Reduce by set intersection
∇ | and return the first element where
⟨:l¦:⌉=¦⟩ | the length is equal to the max length$endgroup$
add a comment |
$begingroup$
Gaia, 15 bytes
eḋ¦&⊢⟨:l¦:⌉=¦⟩∇
Try it online!
e | eval as code
ḋ¦ | find all non-empty substrings
&⊢ | Reduce by set intersection
∇ | and return the first element where
⟨:l¦:⌉=¦⟩ | the length is equal to the max length$endgroup$
add a comment |
$begingroup$
Gaia, 15 bytes
eḋ¦&⊢⟨:l¦:⌉=¦⟩∇
Try it online!
e | eval as code
ḋ¦ | find all non-empty substrings
&⊢ | Reduce by set intersection
∇ | and return the first element where
⟨:l¦:⌉=¦⟩ | the length is equal to the max length$endgroup$
Gaia, 15 bytes
eḋ¦&⊢⟨:l¦:⌉=¦⟩∇
Try it online!
e | eval as code
ḋ¦ | find all non-empty substrings
&⊢ | Reduce by set intersection
∇ | and return the first element where
⟨:l¦:⌉=¦⟩ | the length is equal to the max lengthanswered Mar 26 at 20:11
GiuseppeGiuseppe
17.2k31152
17.2k31152
add a comment |
add a comment |
$begingroup$
PowerShell, 165 163 87 bytes
-76 bytes thanks to Nail for the awesome regexp.
"$($args-join'
'|sls "(?<=^.*)(.+)(?=(.*n.*1)*.*$)"-a -ca|% m*|sort Le*|select -l 1)"
Try it online!
Less golfed:
$multilineArgs = $args-join"`n"
$matches = $multilineArgs|sls "(?<=^.*)(.+)(?=(.*n.*1)*.*$)" -AllMatches -CaseSensitive|% matches
$longestOrNull = $matches|sort Length|select -Last 1
"$longestOrNull"
$endgroup$
add a comment |
$begingroup$
PowerShell, 165 163 87 bytes
-76 bytes thanks to Nail for the awesome regexp.
"$($args-join'
'|sls "(?<=^.*)(.+)(?=(.*n.*1)*.*$)"-a -ca|% m*|sort Le*|select -l 1)"
Try it online!
Less golfed:
$multilineArgs = $args-join"`n"
$matches = $multilineArgs|sls "(?<=^.*)(.+)(?=(.*n.*1)*.*$)" -AllMatches -CaseSensitive|% matches
$longestOrNull = $matches|sort Length|select -Last 1
"$longestOrNull"
$endgroup$
add a comment |
$begingroup$
PowerShell, 165 163 87 bytes
-76 bytes thanks to Nail for the awesome regexp.
"$($args-join'
'|sls "(?<=^.*)(.+)(?=(.*n.*1)*.*$)"-a -ca|% m*|sort Le*|select -l 1)"
Try it online!
Less golfed:
$multilineArgs = $args-join"`n"
$matches = $multilineArgs|sls "(?<=^.*)(.+)(?=(.*n.*1)*.*$)" -AllMatches -CaseSensitive|% matches
$longestOrNull = $matches|sort Length|select -Last 1
"$longestOrNull"
$endgroup$
PowerShell, 165 163 87 bytes
-76 bytes thanks to Nail for the awesome regexp.
"$($args-join'
'|sls "(?<=^.*)(.+)(?=(.*n.*1)*.*$)"-a -ca|% m*|sort Le*|select -l 1)"
Try it online!
Less golfed:
$multilineArgs = $args-join"`n"
$matches = $multilineArgs|sls "(?<=^.*)(.+)(?=(.*n.*1)*.*$)" -AllMatches -CaseSensitive|% matches
$longestOrNull = $matches|sort Length|select -Last 1
"$longestOrNull"
edited 2 days ago
answered 2 days ago
mazzymazzy
2,9351317
2,9351317
add a comment |
add a comment |
$begingroup$
Charcoal, 30 bytes
≔⊟θη≔⁰ζFLη«≔✂ηζ⊕ι¹ε¿⬤θ№κεPε≦⊕ζ
Try it online! Link is to verbose version of code. This algorithm is more efficient as well as shorter than generating all substrings. Explanation:
≔⊟θη
Pop the last string from the input list into a variable.
≔⁰ζ
Zero out the substring start index.
FLη«
Loop over all possible substring end indices. (Actually this loops from 0 excluding the length, so the value is adjusted later.)
≔✂ηζ⊕ι¹ε
Obtain the current substring.
¿⬤θ№κε
Check whether this substring is contained in all of the other input strings.
Pε
If it is then overprint any previously output substring.
≦⊕ζ
Otherwise try incrementing the substring start index.
$endgroup$
add a comment |
$begingroup$
Charcoal, 30 bytes
≔⊟θη≔⁰ζFLη«≔✂ηζ⊕ι¹ε¿⬤θ№κεPε≦⊕ζ
Try it online! Link is to verbose version of code. This algorithm is more efficient as well as shorter than generating all substrings. Explanation:
≔⊟θη
Pop the last string from the input list into a variable.
≔⁰ζ
Zero out the substring start index.
FLη«
Loop over all possible substring end indices. (Actually this loops from 0 excluding the length, so the value is adjusted later.)
≔✂ηζ⊕ι¹ε
Obtain the current substring.
¿⬤θ№κε
Check whether this substring is contained in all of the other input strings.
Pε
If it is then overprint any previously output substring.
≦⊕ζ
Otherwise try incrementing the substring start index.
$endgroup$
add a comment |
$begingroup$
Charcoal, 30 bytes
≔⊟θη≔⁰ζFLη«≔✂ηζ⊕ι¹ε¿⬤θ№κεPε≦⊕ζ
Try it online! Link is to verbose version of code. This algorithm is more efficient as well as shorter than generating all substrings. Explanation:
≔⊟θη
Pop the last string from the input list into a variable.
≔⁰ζ
Zero out the substring start index.
FLη«
Loop over all possible substring end indices. (Actually this loops from 0 excluding the length, so the value is adjusted later.)
≔✂ηζ⊕ι¹ε
Obtain the current substring.
¿⬤θ№κε
Check whether this substring is contained in all of the other input strings.
Pε
If it is then overprint any previously output substring.
≦⊕ζ
Otherwise try incrementing the substring start index.
$endgroup$
Charcoal, 30 bytes
≔⊟θη≔⁰ζFLη«≔✂ηζ⊕ι¹ε¿⬤θ№κεPε≦⊕ζ
Try it online! Link is to verbose version of code. This algorithm is more efficient as well as shorter than generating all substrings. Explanation:
≔⊟θη
Pop the last string from the input list into a variable.
≔⁰ζ
Zero out the substring start index.
FLη«
Loop over all possible substring end indices. (Actually this loops from 0 excluding the length, so the value is adjusted later.)
≔✂ηζ⊕ι¹ε
Obtain the current substring.
¿⬤θ№κε
Check whether this substring is contained in all of the other input strings.
Pε
If it is then overprint any previously output substring.
≦⊕ζ
Otherwise try incrementing the substring start index.
answered 2 days ago
NeilNeil
82.1k745178
82.1k745178
add a comment |
add a comment |
$begingroup$
JavaScript (Node.js), 90 bytes
f=(a,s=e=0,w='')=>a[0][e]?f(a,s+(r=a.some(x=>!x.includes(t),t=a[0].slice(s,++e))),r?w:t):w
Try it online! Test cases shamelessly stolen from @Arnauld. Port of my Charcoal answer.
$endgroup$
add a comment |
$begingroup$
JavaScript (Node.js), 90 bytes
f=(a,s=e=0,w='')=>a[0][e]?f(a,s+(r=a.some(x=>!x.includes(t),t=a[0].slice(s,++e))),r?w:t):w
Try it online! Test cases shamelessly stolen from @Arnauld. Port of my Charcoal answer.
$endgroup$
add a comment |
$begingroup$
JavaScript (Node.js), 90 bytes
f=(a,s=e=0,w='')=>a[0][e]?f(a,s+(r=a.some(x=>!x.includes(t),t=a[0].slice(s,++e))),r?w:t):w
Try it online! Test cases shamelessly stolen from @Arnauld. Port of my Charcoal answer.
$endgroup$
JavaScript (Node.js), 90 bytes
f=(a,s=e=0,w='')=>a[0][e]?f(a,s+(r=a.some(x=>!x.includes(t),t=a[0].slice(s,++e))),r?w:t):w
Try it online! Test cases shamelessly stolen from @Arnauld. Port of my Charcoal answer.
answered 2 days ago
NeilNeil
82.1k745178
82.1k745178
add a comment |
add a comment |
If this is an answer to a challenge…
…Be sure to follow the challenge specification. However, please refrain from exploiting obvious loopholes. Answers abusing any of the standard loopholes are considered invalid. If you think a specification is unclear or underspecified, comment on the question instead.
…Try to optimize your score. For instance, answers to code-golf challenges should attempt to be as short as possible. You can always include a readable version of the code in addition to the competitive one.
Explanations of your answer make it more interesting to read and are very much encouraged.…Include a short header which indicates the language(s) of your code and its score, as defined by the challenge.
More generally…
…Please make sure to answer the question and provide sufficient detail.
…Avoid asking for help, clarification or responding to other answers (use comments instead).
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodegolf.stackexchange.com%2fquestions%2f182134%2fgreatest-common-substring%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
$begingroup$
Possible duplicate
$endgroup$
– Adám
Mar 25 at 0:51
2
$begingroup$
@Adám That question asks for the longest common subsequence, not substring.
$endgroup$
– Doorknob♦
Mar 25 at 0:58
1
$begingroup$
Will the strings be only alphanumeric, or alphabetic, or only printable-ascii?
$endgroup$
– Embodiment of Ignorance
Mar 25 at 1:57
$begingroup$
@EmbodimentofIgnorance All printable ASCII characters can appear in the input.
$endgroup$
– Sara J
Mar 25 at 2:11
2
$begingroup$
@Shaggy Generally, no. If the two can be distinguished,
undefinedimplies there's no valid output string. If the empty string (or any other string) is a valid output, claiming there is no valid output is incorrect.$endgroup$
– Sara J
Mar 25 at 10:03