Merge two strings
Challenge
Given two strings a and b, return the shortest string s so that s starts with a and ends with b.
(Inspired by https://chat.stackexchange.com/transcript/message/57816868#57816868 )
Examples
'ABCDEF', 'EFGHI' -> 'ABCDEFGHI'
'AAAAAA', 'AAAAAAAA' -> 'AAAAAAAA'
'ABC', '123' -> 'ABC123'
'', 'ABCDE' -> 'ABCDE'
'ABCD', 'ABCD' -> 'ABCD'
'', '' -> ''
Brownie points for beating my 26 in APL.
Sed -`E`, 25 bytes Takes se …
5y ago
APL(Dyalog Unicode), 26 bytes …
5y ago
BQN, 18 bytesSBCS ``` {⊑(⊑ …
5y ago
Japt `-h`, 13 12 9 bytes …
5y ago
[Jelly], 13 bytes W;;Ƥ@ …
5y ago
JavaScript, 50 bytes As …
6mo ago
Perl, 43 bytes Takes two st …
6mo ago
Vyxal, 1 byte ``` ⋎ ``` …
5y ago
[Python 3], 82 81 bytes …
5y ago
Ruby, 40 bytes ```ruby f=- …
4y ago
10 answers
You are accessing this answer with a direct link, so it's being shown above all other answers regardless of its score. You can return to the normal view.
Perl, 43 bytes
Takes two strings with arbitrary content.
Returns merged result.
sub f{"@_"=~s/(.*)\K$"(?=\Q$_[1]\E$)\1//sr}
Inspired by Wezl's sed regex.
0 comment threads
Sed -E, 25 bytes
Takes second input, , comma, first input (inputs cannot contain , commas).
s/^(.*)(.*),(.*)\1$/\3\2/
APL(Dyalog Unicode), 26 bytes SBCS
{⊃x/⍨⊃¨⍺∘⍷¨x←,∘⍵¨(⊂⍬),,\⍺}
A dfn submission which takes the inputs as left and right argument.
I took way too long to come up with this. Fun challenge.
0 comment threads
BQN, 18 bytesSBCS
{⊑(⊑𝕨⊸⍷)¨⊸/∾⟜𝕩¨↑𝕨}
A direct translation of Razetime's APL solution (my attempted improvement ⊣∾{⊢´/𝕨⊸«⊸≡¨↑𝕩}↓⊢ turns out to be not at all correct).
The BQN solution is much shorter mainly because it has Prefixes (↑) built in. Being able to filter with ⊸/ (see Before) also helps a lot.
{⊑(⊑𝕨⊸⍷)¨⊸/∾⟜𝕩¨↑𝕨} # Function with left argument 𝕨 and right argument 𝕩
↑𝕨 # All prefixes of 𝕨
∾⟜𝕩¨ # Append 𝕩 after each one
⊸/ # Filter by...
( )¨ # On each string,
𝕨⊸⍷ # Where does 𝕨 appear as a substring?
⊑ # But I only care if it's the first one
⊑ # Then take the first
Put together, the pattern ⊑𝕨⊸⍷ tests if 𝕨 is a prefix of the argument.
0 comment threads
Jelly, 13 bytes
W;;Ƥ@ḣL}¹⁼ʋƇḢ
Takes the two strings as arguments in reverse order.
0 comment threads
Python 3, 82 81 bytes
lambda a,b:[a[:i]+b for i in range(len(a)+2)if i>len(a)or b[:len(a)-i]==a[i:]][0]
0 comment threads
JavaScript, 50 bytes
Assumes, per the test cases, that no RegEx characters will be included in the input. Otherwise, replace search with indexOf.
a=>g=(b,s=n=``)=>(s+b).search(a)?g(b,s+a[n++]):s+b
0 comment threads
Ruby, 40 bytes
f=->a,b{b.index(a)==0?b:a[/./m]+f[$',b]}
If we could assume that string contains only letters and numbers (or to be more specific, no characters like \t\n\v\f\r \#$()*+-.?[\\]^{|}) then it could be improved to 36 bytes:
f=->a,b{b=~/^#{a}/?b:a[/./]+f[$',b]}

3 comment threads