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.
APL(Dyalog Unicode), 26 bytes …
3y ago
Sed -`E`, 25 bytes Takes se …
3y ago
BQN, 18 bytesSBCS ``` {⊑(⊑ …
3y ago
Japt `-h`, 13 12 9 bytes …
3y ago
[Jelly], 13 bytes W;;Ƥ@ …
3y ago
Vyxal, 1 byte ``` ⋎ ``` …
3y ago
[Python 3], 82 81 bytes …
3y ago
Ruby, 40 bytes ```ruby f=- …
3y ago
8 answers
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
Sed -E
, 25 bytes
Takes second input, ,
comma, first input (inputs cannot contain ,
commas).
s/^(.*)(.*),(.*)\1$/\3\2/
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
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