21
3
I recently saw this question on stackoverflow. It's a great question, but there's one fatal problem with the question. They are asking for the best way to do it. E.g, easiest to read, most idiomatic, neatest etc. Don't they know that isn't what matters? You're supposed to ask about how to do it with the fewest bytes of code!
Since I doubt that question will be appreciated on stackoverflow, I decided to ask it here.
The challenge
You must write the shortest possible program or function that generates all possible ways to interleave any two arbitrary strings. For example, if the two strings are 'ab'
and 'cd'
, the output is:
['abcd', 'acbd', 'acdb', 'cabd', 'cadb', 'cdab']
As you can see, a
is always before b
, and c
is always before d
.
IO can be in any reasonable format. Use this python code to verify to check your output. (credit: JeD)
def shuffle(s,t):
if s=="":
return [t]
elif t=="":
return [s]
else:
leftShuffle=[s[0]+val for val in shuffle(s[1:],t)]
rightShuffle=[t[0]+val for val in shuffle(s,t[1:])]
leftShuffle.extend(rightShuffle)
return leftShuffle
Sample IO:
shuffle("$", "1234"):
['$1234', '1$234', '12$34', '123$4', '1234$']
shuffle("az", "by"):
['azby', 'abzy', 'abyz', 'bazy', 'bayz', 'byaz']
shuffle("code", "golf"):
['codegolf', 'codgeolf', 'codgoelf', 'codgolef', 'codgolfe', 'cogdeolf', 'cogdoelf',
'cogdolef', 'cogdolfe', 'cogodelf', 'cogodlef', 'cogodlfe', 'cogoldef', 'cogoldfe',
'cogolfde', 'cgodeolf', 'cgodoelf', 'cgodolef', 'cgodolfe', 'cgoodelf', 'cgoodlef',
'cgoodlfe', 'cgooldef', 'cgooldfe', 'cgoolfde', 'cgoodelf', 'cgoodlef', 'cgoodlfe',
'cgooldef', 'cgooldfe', 'cgoolfde', 'cgolodef', 'cgolodfe', 'cgolofde', 'cgolfode',
'gcodeolf', 'gcodoelf', 'gcodolef', 'gcodolfe', 'gcoodelf', 'gcoodlef', 'gcoodlfe',
'gcooldef', 'gcooldfe', 'gcoolfde', 'gcoodelf', 'gcoodlef', 'gcoodlfe', 'gcooldef',
'gcooldfe', 'gcoolfde', 'gcolodef', 'gcolodfe', 'gcolofde', 'gcolfode', 'gocodelf',
'gocodlef', 'gocodlfe', 'gocoldef', 'gocoldfe', 'gocolfde', 'goclodef', 'goclodfe',
'goclofde', 'goclfode', 'golcodef', 'golcodfe', 'golcofde', 'golcfode', 'golfcode']
As usual, standard loopholes apply, and the shortest answer in bytes wins. Since the question was originally about python, I'd love to see the shortest python answer. (And no, pyth is not python). However, answers in any language are encouraged.
5Fewest bytes of code is the bestest way to do it, every one knows that!* (disclaimer: not CR). – Rɪᴋᴇʀ – 2016-03-29T00:48:13.480
1Are all characters distinct? Or not necessarily? – aditsu quit because SE is EVIL – 2016-03-29T01:53:13.567
4Actually... in your "code", "golf" example you have a duplicate "o" and duplicate results too, e.g. 'gcoodelf'. I'll assume that's what you want. – aditsu quit because SE is EVIL – 2016-03-29T02:04:17.840
1"I just found this great question. However, there is one fatal flaw: they want it done well!" – Cyoce – 2016-03-30T06:43:00.243
1You should provide the sample IO for "aabb","bc". – Taemyr – 2016-03-30T08:34:37.023