Greatest common substringTips for golfing in HaskellLongest common substring in linear timeShortest Longest...
How to check participants in at events?
Can the electrostatic force be infinite in magnitude?
Simulating a probability of 1 of 2^N with less than N random bits
Golf game boilerplate
The most efficient algorithm to find all possible integer pairs which sum to a given integer
Can a Bard use an arcane focus?
Greatest common substring
How to prevent YouTube from showing already watched videos?
Pronouncing Homer as in modern Greek
Organic chemistry Iodoform Reaction
How to color a zone in Tikz
Can somebody explain Brexit in a few child-proof sentences?
What do you call the infoboxes with text and sometimes images on the side of a page we find in textbooks?
Reply ‘no position’ while the job posting is still there (‘HiWi’ position in Germany)
A known event to a history junkie
Can the harmonic series explain the origin of the major scale?
Calculating the number of days between 2 dates in Excel
Does "Dominei" mean something?
Could solar power be utilized and substitute coal in the 19th century?
Why are on-board computers allowed to change controls without notifying the pilots?
What will be the benefits of Brexit?
What does the "3am" section means in manpages?
Visiting the UK as unmarried couple
How can I raise concerns with a new DM about XP splitting?
Greatest common substring
Tips for golfing in HaskellLongest common substring in linear timeShortest Longest Common Subsequence CodeDecompose a StringFind the substring with the most 1's in a sequenceFind Patterns in StringsShortest Longest Common Subsequence CodeMaximal Substring ConstructionVisualize the greatest common divisorShortest Unique SubstringAs Easy As A-B-CFind the original string, without the repetition without the repetition in the middleThe Third String
$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
yesterday
1
$begingroup$
@Adám That question asks for the longest common subsequence, not substring.
$endgroup$
– Doorknob♦
yesterday
1
$begingroup$
Will the strings be only alphanumeric, or alphabetic, or only printable-ascii?
$endgroup$
– Embodiment of Ignorance
yesterday
$begingroup$
@EmbodimentofIgnorance All printable ASCII characters can appear in the input.
$endgroup$
– Sara J
yesterday
1
$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
19 hours ago
|
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 12 hours ago
Toby Speight
4,47711535
4,47711535
asked yesterday
Sara JSara J
2818
2818
$begingroup$
Possible duplicate
$endgroup$
– Adám
yesterday
1
$begingroup$
@Adám That question asks for the longest common subsequence, not substring.
$endgroup$
– Doorknob♦
yesterday
1
$begingroup$
Will the strings be only alphanumeric, or alphabetic, or only printable-ascii?
$endgroup$
– Embodiment of Ignorance
yesterday
$begingroup$
@EmbodimentofIgnorance All printable ASCII characters can appear in the input.
$endgroup$
– Sara J
yesterday
1
$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
19 hours ago
|
show 4 more comments
$begingroup$
Possible duplicate
$endgroup$
– Adám
yesterday
1
$begingroup$
@Adám That question asks for the longest common subsequence, not substring.
$endgroup$
– Doorknob♦
yesterday
1
$begingroup$
Will the strings be only alphanumeric, or alphabetic, or only printable-ascii?
$endgroup$
– Embodiment of Ignorance
yesterday
$begingroup$
@EmbodimentofIgnorance All printable ASCII characters can appear in the input.
$endgroup$
– Sara J
yesterday
1
$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
19 hours ago
$begingroup$
Possible duplicate
$endgroup$
– Adám
yesterday
$begingroup$
Possible duplicate
$endgroup$
– Adám
yesterday
1
1
$begingroup$
@Adám That question asks for the longest common subsequence, not substring.
$endgroup$
– Doorknob♦
yesterday
$begingroup$
@Adám That question asks for the longest common subsequence, not substring.
$endgroup$
– Doorknob♦
yesterday
1
1
$begingroup$
Will the strings be only alphanumeric, or alphabetic, or only printable-ascii?
$endgroup$
– Embodiment of Ignorance
yesterday
$begingroup$
Will the strings be only alphanumeric, or alphabetic, or only printable-ascii?
$endgroup$
– Embodiment of Ignorance
yesterday
$begingroup$
@EmbodimentofIgnorance All printable ASCII characters can appear in the input.
$endgroup$
– Sara J
yesterday
$begingroup$
@EmbodimentofIgnorance All printable ASCII characters can appear in the input.
$endgroup$
– Sara J
yesterday
1
1
$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
19 hours ago
$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
19 hours ago
|
show 4 more comments
23 Answers
23
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
17 hours ago
$begingroup$
Ugh, seems I remembered the tiebreak order fors
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
17 hours ago
$begingroup$
@ais523 The orders
produces substrings is by first giving all prefixes of the input (longest first), then dropping the first one and repeat
$endgroup$
– Kroppeb
12 hours ago
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$
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$
1
$begingroup$
You might as well say that it is Ruby 2.6 and get rid of-1
:)
$endgroup$
– Kirill L.
13 hours 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$
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
19 hours ago
add a comment |
$begingroup$
05AB1E, 14 9 bytes
€Œ.«Ãõªéθ
-5 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
õª # Append an empty string to the remaining list of strings
é # Sort by length
θ # And pop and push its last item (which is output implicitly as result)
$endgroup$
1
$begingroup$
I think€Œ.«Ãõªéθ
should work for 9 bytes.
$endgroup$
– Adnan
15 hours ago
$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
14 hours ago
$begingroup$
Actually, I think€Œ.«ÃéθJ
should work for 8.
$endgroup$
– Adnan
9 hours ago
add a comment |
$begingroup$
Jelly, 12 6 bytes
Ẇ€f/ṫ0
Try it online!
Thanks to @JonathanAllan for saving 6 bytes!
$endgroup$
$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
17 hours ago
$begingroup$
also I thinkœ&/
may be replaced byf/
here saving another
$endgroup$
– Jonathan Allan
17 hours ago
$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
13 hours ago
$begingroup$
@JonathanAllan sounds good. Thanks for the other tips - hope you were happy for me to incorporate them.
$endgroup$
– Nick Kennedy
12 hours ago
$begingroup$
Yes, my reason for those comments was to allow you to incorporate the ideas into your post.
$endgroup$
– Jonathan Allan
12 hours ago
|
show 1 more 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 ofnchar
are enough to save something by declaringnchar
as an unary operator.
$endgroup$
– Kirill L.
13 hours ago
$begingroup$
@KirillL. yes, it is shorter by 2 bytes. Thanks! Aliasinglist
similarly gives us -3 bytes.
$endgroup$
– Giuseppe
12 hours ago
$begingroup$
You can also drop braces for another -2
$endgroup$
– Kirill L.
7 hours ago
$begingroup$
@KirillL. thanks! I'm a bit worried I'm going to start doing that with production code...
$endgroup$
– Giuseppe
7 hours ago
$begingroup$
that's the problem with golfing a language you use every day
$endgroup$
– MickyT
6 hours ago
add a comment |
$begingroup$
Zsh, 126 123 bytes
3 bytes saved via arithmetic for
for l in $@
{a= i=
for ((;i++<$#l**2;)){a+=($l[1+i/$#l,1+i%$#l])}
b=(${${b-$a}:*a})}
for s in $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 in $@; {
a= # empty a
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
}
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 in $b; { # for every common substring
(( $#x < $#s )) && x=$s # if the current word is longer, use it
}
<<<$x # print to stdout
New contributor
$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$
C#, 320 bytes
//method that returns all possible substrings from a string
IEnumerable<string>f(string s){for(int i=0;i<s.Length;i++)for(int j=i;j<s.Length;j++)yield return s.Substring(i,j-i+1);}
//main method
void g(List<string>l){Console.WriteLine(string.Join(",",l.Select(s=>f(s)).Aggregate((a,b)=>a.Intersect(b)).GroupBy(x=>x.Length).OrderBy(x=>x.Key).LastOrDefault()?.Select(y=>y)??new List<string>()));}
Try it online!
Couldn't make it work for https://tio.run/#cs-csc, would be really grateful if someone showed me how to input lists on that site!
The result can be outputted as a collection rather than a string, which would save a few bytes, but it seems like in C#, unlike with other languages, it won't be readable through Console.Writeline, would that still be a valid answer or is there a different workaround?
New contributor
$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
12 hours ago
$begingroup$
Here's the solution golfed down some bytes 215 bytes
$endgroup$
– Expired Data
12 hours ago
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,-F
defaults to the empty string.
$endgroup$
– Shaggy
17 hours 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
$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
yesterday
$begingroup$
@JoKing tio.run/…
$endgroup$
– Artemis Fowl
yesterday
$begingroup$
Right, here's a fixed version of the 135 byte program
$endgroup$
– Jo King
yesterday
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 reduce
s it by set intersection (set.__and__
) and then returns the max
element by len
gth.
$endgroup$
$begingroup$
1 byte shorter withset.intersection
.
$endgroup$
– ovs
17 hours 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$
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
$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$
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$
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$
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$
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$
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$
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 |
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
23 Answers
23
active
oldest
votes
23 Answers
23
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
17 hours ago
$begingroup$
Ugh, seems I remembered the tiebreak order fors
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
17 hours ago
$begingroup$
@ais523 The orders
produces substrings is by first giving all prefixes of the input (longest first), then dropping the first one and repeat
$endgroup$
– Kroppeb
12 hours ago
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
17 hours ago
$begingroup$
Ugh, seems I remembered the tiebreak order fors
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
17 hours ago
$begingroup$
@ais523 The orders
produces substrings is by first giving all prefixes of the input (longest first), then dropping the first one and repeat
$endgroup$
– Kroppeb
12 hours ago
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 16 hours ago
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
17 hours ago
$begingroup$
Ugh, seems I remembered the tiebreak order fors
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
17 hours ago
$begingroup$
@ais523 The orders
produces substrings is by first giving all prefixes of the input (longest first), then dropping the first one and repeat
$endgroup$
– Kroppeb
12 hours ago
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
17 hours ago
$begingroup$
Ugh, seems I remembered the tiebreak order fors
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
17 hours ago
$begingroup$
@ais523 The orders
produces substrings is by first giving all prefixes of the input (longest first), then dropping the first one and repeat
$endgroup$
– Kroppeb
12 hours ago
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
17 hours ago
$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
17 hours ago
$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
17 hours ago
$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
17 hours ago
$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
12 hours ago
$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
12 hours ago
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 yesterday
xnorxnor
92.9k18190447
92.9k18190447
add a comment |
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$
1
$begingroup$
You might as well say that it is Ruby 2.6 and get rid of-1
:)
$endgroup$
– Kirill L.
13 hours ago
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$
1
$begingroup$
You might as well say that it is Ruby 2.6 and get rid of-1
:)
$endgroup$
– Kirill L.
13 hours ago
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 10 hours ago
answered 21 hours ago
G BG B
8,0561429
8,0561429
1
$begingroup$
You might as well say that it is Ruby 2.6 and get rid of-1
:)
$endgroup$
– Kirill L.
13 hours ago
add a comment |
1
$begingroup$
You might as well say that it is Ruby 2.6 and get rid of-1
:)
$endgroup$
– Kirill L.
13 hours ago
1
1
$begingroup$
You might as well say that it is Ruby 2.6 and get rid of
-1
:)$endgroup$
– Kirill L.
13 hours ago
$begingroup$
You might as well say that it is Ruby 2.6 and get rid of
-1
:)$endgroup$
– Kirill L.
13 hours 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$
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
19 hours 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$
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
19 hours 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$
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 yesterday
Jo KingJo King
25.4k362129
25.4k362129
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
19 hours ago
add a comment |
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
19 hours ago
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
19 hours ago
$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
19 hours ago
add a comment |
$begingroup$
05AB1E, 14 9 bytes
€Œ.«Ãõªéθ
-5 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
õª # Append an empty string to the remaining list of strings
é # Sort by length
θ # And pop and push its last item (which is output implicitly as result)
$endgroup$
1
$begingroup$
I think€Œ.«Ãõªéθ
should work for 9 bytes.
$endgroup$
– Adnan
15 hours ago
$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
14 hours ago
$begingroup$
Actually, I think€Œ.«ÃéθJ
should work for 8.
$endgroup$
– Adnan
9 hours ago
add a comment |
$begingroup$
05AB1E, 14 9 bytes
€Œ.«Ãõªéθ
-5 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
õª # Append an empty string to the remaining list of strings
é # Sort by length
θ # And pop and push its last item (which is output implicitly as result)
$endgroup$
1
$begingroup$
I think€Œ.«Ãõªéθ
should work for 9 bytes.
$endgroup$
– Adnan
15 hours ago
$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
14 hours ago
$begingroup$
Actually, I think€Œ.«ÃéθJ
should work for 8.
$endgroup$
– Adnan
9 hours ago
add a comment |
$begingroup$
05AB1E, 14 9 bytes
€Œ.«Ãõªéθ
-5 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
õª # Append an empty string to the remaining list of strings
é # Sort by length
θ # And pop and push its last item (which is output implicitly as result)
$endgroup$
05AB1E, 14 9 bytes
€Œ.«Ãõªéθ
-5 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
õª # Append an empty string to the remaining list of strings
é # Sort by length
θ # And pop and push its last item (which is output implicitly as result)
edited 14 hours ago
answered 18 hours ago
Kevin CruijssenKevin Cruijssen
41.3k567213
41.3k567213
1
$begingroup$
I think€Œ.«Ãõªéθ
should work for 9 bytes.
$endgroup$
– Adnan
15 hours ago
$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
14 hours ago
$begingroup$
Actually, I think€Œ.«ÃéθJ
should work for 8.
$endgroup$
– Adnan
9 hours ago
add a comment |
1
$begingroup$
I think€Œ.«Ãõªéθ
should work for 9 bytes.
$endgroup$
– Adnan
15 hours ago
$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
14 hours ago
$begingroup$
Actually, I think€Œ.«ÃéθJ
should work for 8.
$endgroup$
– Adnan
9 hours ago
1
1
$begingroup$
I think
€Œ.«Ãõªéθ
should work for 9 bytes.$endgroup$
– Adnan
15 hours ago
$begingroup$
I think
€Œ.«Ãõªéθ
should work for 9 bytes.$endgroup$
– Adnan
15 hours ago
$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
14 hours ago
$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
14 hours ago
$begingroup$
Actually, I think
€Œ.«ÃéθJ
should work for 8.$endgroup$
– Adnan
9 hours ago
$begingroup$
Actually, I think
€Œ.«ÃéθJ
should work for 8.$endgroup$
– Adnan
9 hours ago
add a comment |
$begingroup$
Jelly, 12 6 bytes
Ẇ€f/ṫ0
Try it online!
Thanks to @JonathanAllan for saving 6 bytes!
$endgroup$
$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
17 hours ago
$begingroup$
also I thinkœ&/
may be replaced byf/
here saving another
$endgroup$
– Jonathan Allan
17 hours ago
$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
13 hours ago
$begingroup$
@JonathanAllan sounds good. Thanks for the other tips - hope you were happy for me to incorporate them.
$endgroup$
– Nick Kennedy
12 hours ago
$begingroup$
Yes, my reason for those comments was to allow you to incorporate the ideas into your post.
$endgroup$
– Jonathan Allan
12 hours ago
|
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Ẇ€œ&/Ṫḟ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
17 hours ago
$begingroup$
also I thinkœ&/
may be replaced byf/
here saving another
$endgroup$
– Jonathan Allan
17 hours ago
$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
13 hours ago
$begingroup$
@JonathanAllan sounds good. Thanks for the other tips - hope you were happy for me to incorporate them.
$endgroup$
– Nick Kennedy
12 hours ago
$begingroup$
Yes, my reason for those comments was to allow you to incorporate the ideas into your post.
$endgroup$
– Jonathan Allan
12 hours ago
|
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 11 hours ago
answered yesterday
Nick KennedyNick Kennedy
99647
99647
$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
17 hours ago
$begingroup$
also I thinkœ&/
may be replaced byf/
here saving another
$endgroup$
– Jonathan Allan
17 hours ago
$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
13 hours ago
$begingroup$
@JonathanAllan sounds good. Thanks for the other tips - hope you were happy for me to incorporate them.
$endgroup$
– Nick Kennedy
12 hours ago
$begingroup$
Yes, my reason for those comments was to allow you to incorporate the ideas into your post.
$endgroup$
– Jonathan Allan
12 hours ago
|
show 1 more comment
$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
17 hours ago
$begingroup$
also I thinkœ&/
may be replaced byf/
here saving another
$endgroup$
– Jonathan Allan
17 hours ago
$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
13 hours ago
$begingroup$
@JonathanAllan sounds good. Thanks for the other tips - hope you were happy for me to incorporate them.
$endgroup$
– Nick Kennedy
12 hours ago
$begingroup$
Yes, my reason for those comments was to allow you to incorporate the ideas into your post.
$endgroup$
– Jonathan Allan
12 hours ago
$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
17 hours ago
$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
17 hours ago
$begingroup$
also I think
œ&/
may be replaced by f/
here saving another$endgroup$
– Jonathan Allan
17 hours ago
$begingroup$
also I think
œ&/
may be replaced by f/
here saving another$endgroup$
– Jonathan Allan
17 hours ago
$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
13 hours ago
$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
13 hours ago
$begingroup$
@JonathanAllan sounds good. Thanks for the other tips - hope you were happy for me to incorporate them.
$endgroup$
– Nick Kennedy
12 hours ago
$begingroup$
@JonathanAllan sounds good. Thanks for the other tips - hope you were happy for me to incorporate them.
$endgroup$
– Nick Kennedy
12 hours ago
$begingroup$
Yes, my reason for those comments was to allow you to incorporate the ideas into your post.
$endgroup$
– Jonathan Allan
12 hours ago
$begingroup$
Yes, my reason for those comments was to allow you to incorporate the ideas into your post.
$endgroup$
– Jonathan Allan
12 hours ago
|
show 1 more 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 ofnchar
are enough to save something by declaringnchar
as an unary operator.
$endgroup$
– Kirill L.
13 hours ago
$begingroup$
@KirillL. yes, it is shorter by 2 bytes. Thanks! Aliasinglist
similarly gives us -3 bytes.
$endgroup$
– Giuseppe
12 hours ago
$begingroup$
You can also drop braces for another -2
$endgroup$
– Kirill L.
7 hours ago
$begingroup$
@KirillL. thanks! I'm a bit worried I'm going to start doing that with production code...
$endgroup$
– Giuseppe
7 hours ago
$begingroup$
that's the problem with golfing a language you use every day
$endgroup$
– MickyT
6 hours ago
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 ofnchar
are enough to save something by declaringnchar
as an unary operator.
$endgroup$
– Kirill L.
13 hours ago
$begingroup$
@KirillL. yes, it is shorter by 2 bytes. Thanks! Aliasinglist
similarly gives us -3 bytes.
$endgroup$
– Giuseppe
12 hours ago
$begingroup$
You can also drop braces for another -2
$endgroup$
– Kirill L.
7 hours ago
$begingroup$
@KirillL. thanks! I'm a bit worried I'm going to start doing that with production code...
$endgroup$
– Giuseppe
7 hours ago
$begingroup$
that's the problem with golfing a language you use every day
$endgroup$
– MickyT
6 hours ago
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 7 hours ago
answered 13 hours ago
GiuseppeGiuseppe
17.1k31152
17.1k31152
$begingroup$
I don't have time to check, but if I'm not mistaken, 2 occurrences ofnchar
are enough to save something by declaringnchar
as an unary operator.
$endgroup$
– Kirill L.
13 hours ago
$begingroup$
@KirillL. yes, it is shorter by 2 bytes. Thanks! Aliasinglist
similarly gives us -3 bytes.
$endgroup$
– Giuseppe
12 hours ago
$begingroup$
You can also drop braces for another -2
$endgroup$
– Kirill L.
7 hours ago
$begingroup$
@KirillL. thanks! I'm a bit worried I'm going to start doing that with production code...
$endgroup$
– Giuseppe
7 hours ago
$begingroup$
that's the problem with golfing a language you use every day
$endgroup$
– MickyT
6 hours ago
add a comment |
$begingroup$
I don't have time to check, but if I'm not mistaken, 2 occurrences ofnchar
are enough to save something by declaringnchar
as an unary operator.
$endgroup$
– Kirill L.
13 hours ago
$begingroup$
@KirillL. yes, it is shorter by 2 bytes. Thanks! Aliasinglist
similarly gives us -3 bytes.
$endgroup$
– Giuseppe
12 hours ago
$begingroup$
You can also drop braces for another -2
$endgroup$
– Kirill L.
7 hours ago
$begingroup$
@KirillL. thanks! I'm a bit worried I'm going to start doing that with production code...
$endgroup$
– Giuseppe
7 hours ago
$begingroup$
that's the problem with golfing a language you use every day
$endgroup$
– MickyT
6 hours ago
$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.
13 hours ago
$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.
13 hours ago
$begingroup$
@KirillL. yes, it is shorter by 2 bytes. Thanks! Aliasing
list
similarly gives us -3 bytes.$endgroup$
– Giuseppe
12 hours ago
$begingroup$
@KirillL. yes, it is shorter by 2 bytes. Thanks! Aliasing
list
similarly gives us -3 bytes.$endgroup$
– Giuseppe
12 hours ago
$begingroup$
You can also drop braces for another -2
$endgroup$
– Kirill L.
7 hours ago
$begingroup$
You can also drop braces for another -2
$endgroup$
– Kirill L.
7 hours ago
$begingroup$
@KirillL. thanks! I'm a bit worried I'm going to start doing that with production code...
$endgroup$
– Giuseppe
7 hours ago
$begingroup$
@KirillL. thanks! I'm a bit worried I'm going to start doing that with production code...
$endgroup$
– Giuseppe
7 hours ago
$begingroup$
that's the problem with golfing a language you use every day
$endgroup$
– MickyT
6 hours ago
$begingroup$
that's the problem with golfing a language you use every day
$endgroup$
– MickyT
6 hours ago
add a comment |
$begingroup$
Zsh, 126 123 bytes
3 bytes saved via arithmetic for
for l in $@
{a= i=
for ((;i++<$#l**2;)){a+=($l[1+i/$#l,1+i%$#l])}
b=(${${b-$a}:*a})}
for s in $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 in $@; {
a= # empty a
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
}
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 in $b; { # for every common substring
(( $#x < $#s )) && x=$s # if the current word is longer, use it
}
<<<$x # print to stdout
New contributor
$endgroup$
add a comment |
$begingroup$
Zsh, 126 123 bytes
3 bytes saved via arithmetic for
for l in $@
{a= i=
for ((;i++<$#l**2;)){a+=($l[1+i/$#l,1+i%$#l])}
b=(${${b-$a}:*a})}
for s in $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 in $@; {
a= # empty a
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
}
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 in $b; { # for every common substring
(( $#x < $#s )) && x=$s # if the current word is longer, use it
}
<<<$x # print to stdout
New contributor
$endgroup$
add a comment |
$begingroup$
Zsh, 126 123 bytes
3 bytes saved via arithmetic for
for l in $@
{a= i=
for ((;i++<$#l**2;)){a+=($l[1+i/$#l,1+i%$#l])}
b=(${${b-$a}:*a})}
for s in $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 in $@; {
a= # empty a
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
}
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 in $b; { # for every common substring
(( $#x < $#s )) && x=$s # if the current word is longer, use it
}
<<<$x # print to stdout
New contributor
$endgroup$
Zsh, 126 123 bytes
3 bytes saved via arithmetic for
for l in $@
{a= i=
for ((;i++<$#l**2;)){a+=($l[1+i/$#l,1+i%$#l])}
b=(${${b-$a}:*a})}
for s in $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 in $@; {
a= # empty a
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
}
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 in $b; { # for every common substring
(( $#x < $#s )) && x=$s # if the current word is longer, use it
}
<<<$x # print to stdout
New contributor
edited 30 mins ago
New contributor
answered yesterday
GammaFunctionGammaFunction
1215
1215
New contributor
New contributor
add a comment |
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 21 hours ago
answered 21 hours ago
LaikoniLaikoni
20.3k439103
20.3k439103
add a comment |
add a comment |
$begingroup$
C#, 320 bytes
//method that returns all possible substrings from a string
IEnumerable<string>f(string s){for(int i=0;i<s.Length;i++)for(int j=i;j<s.Length;j++)yield return s.Substring(i,j-i+1);}
//main method
void g(List<string>l){Console.WriteLine(string.Join(",",l.Select(s=>f(s)).Aggregate((a,b)=>a.Intersect(b)).GroupBy(x=>x.Length).OrderBy(x=>x.Key).LastOrDefault()?.Select(y=>y)??new List<string>()));}
Try it online!
Couldn't make it work for https://tio.run/#cs-csc, would be really grateful if someone showed me how to input lists on that site!
The result can be outputted as a collection rather than a string, which would save a few bytes, but it seems like in C#, unlike with other languages, it won't be readable through Console.Writeline, would that still be a valid answer or is there a different workaround?
New contributor
$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
12 hours ago
$begingroup$
Here's the solution golfed down some bytes 215 bytes
$endgroup$
– Expired Data
12 hours ago
add a comment |
$begingroup$
C#, 320 bytes
//method that returns all possible substrings from a string
IEnumerable<string>f(string s){for(int i=0;i<s.Length;i++)for(int j=i;j<s.Length;j++)yield return s.Substring(i,j-i+1);}
//main method
void g(List<string>l){Console.WriteLine(string.Join(",",l.Select(s=>f(s)).Aggregate((a,b)=>a.Intersect(b)).GroupBy(x=>x.Length).OrderBy(x=>x.Key).LastOrDefault()?.Select(y=>y)??new List<string>()));}
Try it online!
Couldn't make it work for https://tio.run/#cs-csc, would be really grateful if someone showed me how to input lists on that site!
The result can be outputted as a collection rather than a string, which would save a few bytes, but it seems like in C#, unlike with other languages, it won't be readable through Console.Writeline, would that still be a valid answer or is there a different workaround?
New contributor
$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
12 hours ago
$begingroup$
Here's the solution golfed down some bytes 215 bytes
$endgroup$
– Expired Data
12 hours ago
add a comment |
$begingroup$
C#, 320 bytes
//method that returns all possible substrings from a string
IEnumerable<string>f(string s){for(int i=0;i<s.Length;i++)for(int j=i;j<s.Length;j++)yield return s.Substring(i,j-i+1);}
//main method
void g(List<string>l){Console.WriteLine(string.Join(",",l.Select(s=>f(s)).Aggregate((a,b)=>a.Intersect(b)).GroupBy(x=>x.Length).OrderBy(x=>x.Key).LastOrDefault()?.Select(y=>y)??new List<string>()));}
Try it online!
Couldn't make it work for https://tio.run/#cs-csc, would be really grateful if someone showed me how to input lists on that site!
The result can be outputted as a collection rather than a string, which would save a few bytes, but it seems like in C#, unlike with other languages, it won't be readable through Console.Writeline, would that still be a valid answer or is there a different workaround?
New contributor
$endgroup$
C#, 320 bytes
//method that returns all possible substrings from a string
IEnumerable<string>f(string s){for(int i=0;i<s.Length;i++)for(int j=i;j<s.Length;j++)yield return s.Substring(i,j-i+1);}
//main method
void g(List<string>l){Console.WriteLine(string.Join(",",l.Select(s=>f(s)).Aggregate((a,b)=>a.Intersect(b)).GroupBy(x=>x.Length).OrderBy(x=>x.Key).LastOrDefault()?.Select(y=>y)??new List<string>()));}
Try it online!
Couldn't make it work for https://tio.run/#cs-csc, would be really grateful if someone showed me how to input lists on that site!
The result can be outputted as a collection rather than a string, which would save a few bytes, but it seems like in C#, unlike with other languages, it won't be readable through Console.Writeline, would that still be a valid answer or is there a different workaround?
New contributor
New contributor
answered 17 hours ago
Innat3Innat3
1213
1213
New contributor
New contributor
$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
12 hours ago
$begingroup$
Here's the solution golfed down some bytes 215 bytes
$endgroup$
– Expired Data
12 hours 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
12 hours ago
$begingroup$
Here's the solution golfed down some bytes 215 bytes
$endgroup$
– Expired Data
12 hours 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
12 hours 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
12 hours ago
$begingroup$
Here's the solution golfed down some bytes 215 bytes
$endgroup$
– Expired Data
12 hours ago
$begingroup$
Here's the solution golfed down some bytes 215 bytes
$endgroup$
– Expired Data
12 hours ago
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,-F
defaults to the empty string.
$endgroup$
– Shaggy
17 hours ago
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,-F
defaults to the empty string.
$endgroup$
– Shaggy
17 hours ago
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 10 hours ago
answered yesterday
Embodiment of IgnoranceEmbodiment of Ignorance
2,168125
2,168125
$begingroup$
You shouldn't need to sort by length at the end, saving 3 bytes. Also,-F
defaults to the empty string.
$endgroup$
– Shaggy
17 hours ago
add a comment |
$begingroup$
You shouldn't need to sort by length at the end, saving 3 bytes. Also,-F
defaults to the empty string.
$endgroup$
– Shaggy
17 hours ago
$begingroup$
You shouldn't need to sort by length at the end, saving 3 bytes. Also,
-F
defaults to the empty string.$endgroup$
– Shaggy
17 hours ago
$begingroup$
You shouldn't need to sort by length at the end, saving 3 bytes. Also,
-F
defaults to the empty string.$endgroup$
– Shaggy
17 hours 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
$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
yesterday
$begingroup$
@JoKing tio.run/…
$endgroup$
– Artemis Fowl
yesterday
$begingroup$
Right, here's a fixed version of the 135 byte program
$endgroup$
– Jo King
yesterday
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
$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
yesterday
$begingroup$
@JoKing tio.run/…
$endgroup$
– Artemis Fowl
yesterday
$begingroup$
Right, here's a fixed version of the 135 byte program
$endgroup$
– Jo King
yesterday
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
$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
edited yesterday
New contributor
answered yesterday
Artemis FowlArtemis Fowl
1114
1114
New contributor
New contributor
$begingroup$
You may want to use single spaces as indentation instead of 4 that seems to shave more than 100 bytes.
$endgroup$
– Shieru Asakoto
yesterday
$begingroup$
@JoKing tio.run/…
$endgroup$
– Artemis Fowl
yesterday
$begingroup$
Right, here's a fixed version of the 135 byte program
$endgroup$
– Jo King
yesterday
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
yesterday
$begingroup$
@JoKing tio.run/…
$endgroup$
– Artemis Fowl
yesterday
$begingroup$
Right, here's a fixed version of the 135 byte program
$endgroup$
– Jo King
yesterday
$begingroup$
You may want to use single spaces as indentation instead of 4 that seems to shave more than 100 bytes.
$endgroup$
– Shieru Asakoto
yesterday
$begingroup$
You may want to use single spaces as indentation instead of 4 that seems to shave more than 100 bytes.
$endgroup$
– Shieru Asakoto
yesterday
$begingroup$
@JoKing tio.run/…
$endgroup$
– Artemis Fowl
yesterday
$begingroup$
@JoKing tio.run/…
$endgroup$
– Artemis Fowl
yesterday
$begingroup$
Right, here's a fixed version of the 135 byte program
$endgroup$
– Jo King
yesterday
$begingroup$
Right, here's a fixed version of the 135 byte program
$endgroup$
– Jo King
yesterday
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 reduce
s it by set intersection (set.__and__
) and then returns the max
element by len
gth.
$endgroup$
$begingroup$
1 byte shorter withset.intersection
.
$endgroup$
– ovs
17 hours ago
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 reduce
s it by set intersection (set.__and__
) and then returns the max
element by len
gth.
$endgroup$
$begingroup$
1 byte shorter withset.intersection
.
$endgroup$
– ovs
17 hours ago
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 reduce
s it by set intersection (set.__and__
) and then returns the max
element by len
gth.
$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 reduce
s it by set intersection (set.__and__
) and then returns the max
element by len
gth.
edited yesterday
answered yesterday
Jo KingJo King
25.4k362129
25.4k362129
$begingroup$
1 byte shorter withset.intersection
.
$endgroup$
– ovs
17 hours ago
add a comment |
$begingroup$
1 byte shorter withset.intersection
.
$endgroup$
– ovs
17 hours ago
$begingroup$
1 byte shorter with
set.intersection
.$endgroup$
– ovs
17 hours ago
$begingroup$
1 byte shorter with
set.intersection
.$endgroup$
– ovs
17 hours 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 17 hours ago
answered 20 hours ago
ShaggyShaggy
18.9k21667
18.9k21667
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
$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
$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
$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
edited 15 hours ago
answered 18 hours ago
t-clausen.dkt-clausen.dk
1,994314
1,994314
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 12 hours ago
answered 12 hours ago
Nahuel FouilleulNahuel Fouilleul
2,925211
2,925211
add a comment |
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 19 hours ago
Olivier GrégoireOlivier Grégoire
9,31511944
9,31511944
add a comment |
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 14 hours ago
answered 14 hours ago
Expired DataExpired Data
2686
2686
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 11 hours ago
answered 14 hours ago
ArnauldArnauld
79.6k797330
79.6k797330
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 10 hours ago
answered 17 hours ago
Galen IvanovGalen Ivanov
7,26211034
7,26211034
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 7 hours ago
Kjetil S.Kjetil S.
58925
58925
add a comment |
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$
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$
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 4 hours ago
answered 4 hours ago
NeilNeil
82k745178
82k745178
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 4 hours ago
answered yesterday
Shieru AsakotoShieru Asakoto
2,750317
2,750317
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
yesterday
1
$begingroup$
@Adám That question asks for the longest common subsequence, not substring.
$endgroup$
– Doorknob♦
yesterday
1
$begingroup$
Will the strings be only alphanumeric, or alphabetic, or only printable-ascii?
$endgroup$
– Embodiment of Ignorance
yesterday
$begingroup$
@EmbodimentofIgnorance All printable ASCII characters can appear in the input.
$endgroup$
– Sara J
yesterday
1
$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
19 hours ago