title: Construct a word ladder

text:
# Question
Title: Construct a word ladder
Given a list of at least two words (made only of lowercase letters), construct and display an ASCII ladder of the words by alternating the direction of writing first to the right, then to the left, relatively to the initial direction from left to right.

When you finish writing a word, change the direction and only then start writing the next word.

If your language doesn't support lists of words, or it's more convenient for you, you can take the input as a string of words, separated by a single space.

Leading and trailing whitespaces are allowed.

`["hello", "world"]` or `"hello world"`

```
hello
    w
    o
    r
    l
    d

```

Here we start by writing `hello` and when we come to the next word (or in the case of the input as a string - a space is found), we change the relative direction to the right and continue to write `world`

## Test cases:

```
["another", "test", "string"] or "another test string" ->

another
      t
      e
      s
      tstring

["programming", "puzzles", "and", "code", "golf"] or "programming puzzles and code golf" ->

programming
          p
          u
          z
          z
          l
          e
          sand
             c
             o
             d
             egolf

["a", "single", "a"] or "a single a" ->

a
s
i
n
g
l
ea

```

## Wining criteria

The shortest code in bytes in every language wins. Don't let be discouraged by the golfing languages!

Sandbox

# Answer
> 12 votes
# Charcoal, 9 bytes

```
Ｆ⮌Ａ«↑⮌ι‖↗

```

Try it online! Link is to verbose version of code. Explanation: Works by drawing the text backwards, transposing the canvas after every word. 10 bytes for string input:

```
Ｆ⮌Ｓ≡ι ‖↗←ι

```

Try it online! Link is to verbose version of code. Explanation: Draws the text backwards, transposing the canvas for spaces.

# Answer
> 9 votes
# C (gcc), ~~94~~ ~~78~~ 74 bytes

-4 from Johan du Toit

```
o,f;g(int*s){for(o=f=0;*s;s++)*s<33?f=!f:printf("\n%*c"+!f,f*(o+=!f),*s);}

```

Try it online!

Prints the ladder, one character (of the input) at a time. Takes a space-separated string of words.

# Answer
> 6 votes
# 05AB1E, ~~19~~ 16 bytes

```
€θ¨õšøíJD€gs24SΛ

```

-3 bytes thanks to *@Emigna*.

Try it online.

**General explanation:**

Just like *@Emigna*'s 05AB1E answer (make sure to upvote him btw!!), I use the Canvas builtin `Λ`.

The options I use are different however (which is why my answer is longer..):

* `b` (the strings to print): I leave the first string in the list unchanged, and add the trailing character to each next string in the list. For example `["abc","def","ghi","jklmno"]` would become `["abc","cdef","fghi","ijklmno"]`.
* `a` (the sizes of the lines): This would be equal to these strings, so `[3,4,4,7]` with the example above.
* `c` (the direction to print in): `[2,4]`, which would map to `[→,↓,→,↓,→,↓,...]`

So the example above would step-by-step do the following:

1. Draw `abc` in direction `2`/.
2. Draw `cdef` in direction `4`/ (where the first character overlaps with the last character, which is why we had to modify the list like this)
3. Draw `fghi` in direction `2`/ again (also with overlap of trailing/leading characters)
4. Draw `ijklmno` in direction `4`/ again (also with overlap)
5. Output the result of the drawn Canvas immediately to STDOUT

**Code explanation:**

```
€θ                # Only leave the last characters in the (implicit) input-list
  ¨               # Remove the last one
   õš             # And prepend an empty string "" instead
     ø            # Create pairs with the (implicit) input-list
      í           # Reverse each pair
       J          # And then join each pair together to single strings
        D€g       # Get the length of each string (without popping by duplicating first)
           s      # Swap so the lengths are before the strings
            24S   # Push [2,4]
               Λ  # Use the Canvas builtin (which outputs immediately implicitly)

```

# Answer
> 5 votes
# 05AB1E, ~~14~~ 13 bytes

Saved 1 byte thanks to *Grimy*

```
€ðÀD€g>sŽ9÷SΛ

```

Try it online!

**Explanation**

```
                 # example input ["Hello", "World"]
€ðÀ              # push a space after each word
                 # STACK: ["Hello"," ","World"," "]
   D             # duplicate
    €g>          # get the length of each word in the copy and add 1
                 # these are the lengths to draw
                 # STACK: ["Hello"," ","World"," "], [6, 2, 6, 2]
       s         # swap the list of word to the top of the stack
        Ž9÷S     # push [2, 5, 4, 1]
                 # this is the list of directions to draw
                 # 1=northeast, 2=east, 4=south, 5=southwest
            Λ    # paint on canvas

```

# Answer
> 5 votes
# Canvas, ~~17~~ ~~12~~ ~~11~~ 10 bytes

```
ø⁸⇵｛⟳Ｋ└×∔⤢

```

Try it here!

Explanation:

```
ø⁸⇵{⟳K└×∔⤢  full program taking array as input (loaded with ⁸)

ø         push an empty canvas               ["test", "str"], ""
 ⁸⇵{      for each input word, in reverse:   "str", "test" (showing 2nd iter)
    ⟳       rotate the word vertically       "str", "t¶e¶s¶t"
     K      pop off the last letter          "str", "t¶e¶s", "t"
      └     swap the two items below top     "t¶e¶s", "str", "t"
       ×    prepend                          "t¶e¶s", "tstr"
        ∔   vertically append                "t¶e¶s¶tstr"
         ⤢  transpose the canvas             "test
                                                 s
                                                 t
                                                 r"

```

# Answer
> 5 votes
# JavaScript (ES8),  ~~91 79~~  77 bytes

Takes input as an array of words.

```
a=>a.map((s,i)=>i&1?[...s].join(p):s+=p+=''.padEnd(s.length-!i),p=`
`).join``

```

Try it online!

### Commented

```
a =>                 // a[] = input array
  a.map((s, i) =>    // for each word s at position i in a[]:
    i & 1 ?          //   if this is a vertical word:
      [...s].join(p) //     split s and join it with p
    :                //   else:
      s +=           //     add to s:
        p +=         //       add to p:
          ''.padEnd( //         as many spaces
            s.length //         as there are letters in s
            - !i     //         minus 1 if this is the 1st word (because it's not connected
          ),         //         with the last letter of the previous vertical word)
    p = `\n`         //   start with p = linefeed
  ).join``           // end of map(); join everything

```

# Answer
> 5 votes
# Python 2, 82 bytes

```
b=p=0
r=''
for w in input():
 for c in w:r+='\n'.ljust(p)*b+c;p+=1-b
 b^=1
print r

```

Try it online!

# Answer
> 5 votes
# JavaScript, 62 bytes

```
a=>' '+a.replace(/./g,c=>1-c?(a=!a,''):a?(p+=' ',c):p+c,p=`
`)

```

Try it online!

Thanks Rick Hitchcock, 2 bytes saved.

---

# JavaScript, 65 bytes

```
a=>a.replace(/./g,c=>1-c?(t=!t,''):t?p+c:(p+=p?' ':`
`,c),t=p='')

```

Try it online!

```
a=>a.replace(/./g,c=>( // for each character c in string a
    1 - c ?            //   if (c is space)
      (t = !t,         //     update t: boolean value describe word index
                       //       truthy: odd indexed words;
                       //       falsy: even indexed words
        '') :          //     generate nothing for space
    t?                 //   if (is odd index) which means is vertical
      p+c :            //     add '\n', some spaces, and a sigle charater
                       //   else
      (p+=p?' ':'\n',  //     prepare the prepend string for vertical words
         c)            //     add a single character
),
  t=p=''               //   initialize
)

```

# Answer
> 5 votes
# brainfuck, 57 bytes

```
->,[[.<+>,],[<<[-]++++++++++.--[-<++++>]>[-<+<.>>]>.<,],]

```

Try it online!

Takes input as NUL separated strings. Note that this is using EOF as 0, and will stop working when the ladder exceeds 256 spaces.

### Explanation:

```
-           Initialise counter as -1
>,[         Start ladder
   [.<+>,]  Print the first word, adding the length of it to the counter
   ,[       Loop over each letter of the second word
      <<[-]++++++++++.    Print a newline
      --[-<++++>]         Create a space character
      >[-<+<.>>]          Print counter many spaces
      >.<,                Print the letter and move to the next letter
   ]
   ,        Repeat until there are no more words
]

```

# Answer
> 5 votes
# Aheui (esotope), ~~490~~ ~~458~~ 455 bytes

```
삭뱃밸때샏배샐배새뱄밿때빠뱋빼쌘투＠밧우
＠두내백뱃빼선대내백뱃섣＠여우샐처샐추
희차＠＠＠뭏누번사＠빼뭏오추뻐＠＠＠배
Ｂｙ＠＠＠새대백＠＠＠우뻐색
Ｌｅｇｅｎ＠＠빼쵸누번＠＠빼
ＤＵＳＴ＠＠＠샌뽀터본섣숃멓
＠＠＠＠＠＠＠오어아＠먛요아＠＠샏매우
＠＠＠＠＠아＠＠＠＠＠＠오＠＠＠＠＠서어
＠＠＠＠＠희차＠＠요

```

Try it online!

Slightly golfed by using full-width characters(2 bytes) instead Korean(3 bytes).

# Explanation

Aheui is befunge-like esolang. Here is code with color:  ?1 part checks if current character is space or not.

?2 parts check whether words had written right-to-left or top-to-down.

?3 part is break condition of loop which types spaces.

?4 parts check if current character is end of line(-1).

Red part is stack initialization. Aheui uses stacks (from `Nothing` to  : 28 stacks) to store value.

Orange part takes input() and check if it is space, by subtracting with `32`(ascii code of space).

Green part add 1 to stack which stores value of length of space, if writing right-to-left.

Purple part is loop for printing spaces, if writing up-to-down.

Grey part check if current character is `-1`, by adding one to current character.

Blue part prints current character, and prepare for next character.

# Answer
> 4 votes
# Perl 6, 65 bytes

```
{$/=0;.map:{$/+=$++%2??!.comb.fmt("%$/s","
").print!!.say*.comb}}

```

Try it online!

Anonymous code block that takes a list of words and prints straight to STDOUT.

### Explanation

```
{                           }  # Anonymous code block
 $/=0;                         # Initialise $/ to 0
 .map:{                    }   # Map the list of words to
       $/+=                    # Increment $/ by
           $++%2??             # For even indexes
                   .comb       # Each letter of the word
                   .fmt(           ) # Formatted as
                        "%$/s"       # Padded with $/-1 spaces
                              ,"\n"  # Joined by newlines
                   .print            # And printed without a newline
                  !   # Boolean not this to add 0 to $/
                !!            # For odd indexes
                  .say        # Print with a newline
                      *.comb  # And add the length of the word

```

# Answer
> 4 votes
# Japt `-P`, 15 bytes

```
ò mrÈ+R+YÕùT±Xl

```

Try it

```
ò mrÈ+R+YÕùT±Xl     :Implicit input of string array
ò                   :Partition into 2s
  m                 :Map each pair
   r                :  Reduce by
    È               :  Passing through the following function as X & Y
     +              :    Append to X
      R             :    Newline
       +            :    Append
        YÕ          :    Transpose Y
          ù         :    Left pad each line with spaces to length
           T±       :      T (initially 0) incremented by
             Xl     :      Length of X
                    :Implicitly join and output

```

# Answer
> 4 votes
## bash, 119 chars

```
X=("\e7" "\n\e8")
w="$@"
l=${#w}
d=0
for((i=0;i<l;i++));do
c="${w:$i:1}"
[ -z $c ]&&d=$((1-d))||printf ${X[$d]}$c
done

```

This uses ANSI control sequences to move the cursor - here I'm only using save `\e7` and restore `\e8`; but the restore has to be prefixed with `\n` to scroll the output if it's already at the bottom of the terminal. For some reason it doesn't work if you're not *already* at the bottom of the terminal. * shrug *

The current character `$c` is isolated as a single-character substring from the input string `$w`, using the `for` loop index `$i` as the index into the string.

The only real trick I'm using here is `[ -z $c ]` which will return `true`, i.e. the string is blank, when `$c` is a space, because it's unquoted. In correct usage of bash, you would quote the string being tested with `-z` to avoid exactly this situation. This allows us flip the direction flag `$d` between `1` and `0`, which is then used as an index into the ANSI control sequence array, `X` on the next non-space value of `$c`.

I'd be interested to see something that uses `printf "%${x}s" $c`.

Oh gosh let's add some whitespace. I can't see where I am...

```
X=("\e7" "\n\e8")
w="$@"
l=${#w}
d=0
for ((i=0;i<l;i++)); do
  c="${w:$i:1}"
  [ -z $c ] && d=$((1-d)) || printf ${X[$d]}$c
done

```

# Answer
> 3 votes
# Charcoal, 19 bytes

```
ＦＬθ¿﹪ι²«↓§θι↗»«§θι↙

```

Input as a list of strings

Try it online (verbose) or try it online (pure)

**Explanation:**

Loop in the range `[0, input-length)`:

```
For(Length(q))
ＦＬθ

```

If the index is odd:

```
If(Modulo(i,2)){...}
﹪ι²«...»

```

Print the string at index `i` in a downward direction:

```
Print(:Down, AtIndex(q,i));
↓§θι

```

And then move the cursor once towards the top-right:

```
Move(:UpRight);
↗

```

Else (the index is even):

```
Else{...}
«...

```

Print the string at index `i` in a regular right direction:

```
Print(AtIndex(q,i));
§θι

```

And then move the cursor once towards the bottom-left:

```
Move(:DownLeft);
↙

```

# Answer
> 3 votes
# Python 2, ~~89~~ 88 bytes

```
s=i=-1
r=''
for w in input():r+=[('\n'+' '*s).join(' '+w),w][i];s-=i*len(w);i=~i
print r

```

Try it online!

# Answer
> 3 votes
# , <sup>~~47~~ ~~45~~</sup> 43 bytes

```
;[`(([:<@(+/)\#&>##$#:@1 2)@])`([' '"0/[)}]

```

Try it online!

I found a fun, different approach...

I started messing around with left pads and zips with cyclic gerunds and so on, but then I realized it would be easier to just calculate each letter's position (this boils down to a scan sum of the correctly chosen array) and apply amend `}` to a blank canvas on the razed input.

The solution is handled almost entirely by Amend `}`:

```
; [`(([: <@(+/)\ #&> # # $ #:@1 2)@])`([ ' '"0/ [)} ]

```
* `; ( single verb that does all the work ) ]` overall fork
* `;` left part razes the input, ie, puts all the letters into a contiguous string
* `]` right part is the input itself
* `(stuff)}` we use the gerund form of amend `}`, which consists of three parts `v0`v1`v2`.
    + `v0` gives us the "new values", which is the raze (ie, all the characters of the input as one string), so we use `[`.
    + `v2` gives us the starting value, which we are transforming. we simply want a blank canvas of spaces of the needed dimensions. `([ ' '"0/ [)` gives us one of size `(all chars)x(all chars)`.
    + The middle verb `v1` selects which positions we will put our replacement characters in. This is the crux of the logic...
* Starting at position `0 0` in the upper left, we notice that each new character is either 1 to the right of the previous position (ie, `prev + 0 1`) or one down (ie, `prev + 1 0`). Indeed we do the former "len of word 1" times, then the latter "len of word 2" times, and so on, alternating. So we'll just create the correct sequence of these movements, then scan sum them, and we'll have our positions, which we then box because that's how Amend works. What follows is just the mechanics of this idea...
* `([: <@(+/)\ #&> # # $ 1 - e.@0 1)`
    + First `#:@1 2` creates the constant matrix `0 1;1 0`.
    + `# $` then extends it so it has as many rows as the input. eg, if the input contains 3 words it will produce `0 1;1 0;0 1`.
    + `#&> #` the left part of that is an array of the lengths of the input words and `#` is copy, so it copies `0 1` "len of word 1" times, then `1 0` "len of word 2 times", etc.
    + `[: <@(+/)\` does the scan sum and box.

# Answer
> 3 votes
# C# (Visual C# Interactive Compiler), 122 bytes

```
a=>{int i=0;var t="\n";foreach(var z in a)Write(i++%2<1?z+(t+="".PadRight(z.Length-(i<2?1:0))):string.Join(t,z.Skip(0)));}

```

Try it online!

# Answer
> 3 votes
# T-SQL, 185 bytes

```
DECLARE @ varchar(max)='Thomas Clausen Codegolf Script'
,@b bit=0,@s INT=0SET @+=':'WHILE @ like'%_:%'SELECT
@b+=len(left(@,1))-1,@=stuff(@,1,1,'')+iif(left(@,@b)='','','
'+space(@s))+trim(left(@,1)),@s+=len(left(@,~@b))PRINT
stuff(@,1,1,'')

```

**Try it online**

# Answer
> 2 votes
# Retina, 51 bytes

```
1,2,`\w+
;$&
+(m`^(.(.*?)) ?;(.)
$1¶$.2* $3;
; |;$

```

Try it online!

A rather straightforward approach that marks every other word and then applies the transformation directly.

### Explanation

```
1,2,`\w+
;$&

```

We mark every other word with a semicolon by matching each word, but only applying the replacement to the matches (which are zero indexed) starting from match 1 and then 3 and so on.

```
+(m`^(.(.*?)) ?;(.)
$1¶$.2* $3;

```

`+(m` sets some properties for the following stages. The plus begins a "while this group of stages changes something" loop, and the open bracket denotes that the plus should apply to all of the following stages until there is a close bracket in front of a backtick (which is all of the stages in this case). The `m` just tells the regex to treat `^` as also matching from the beginning of lines instead of just the beginning of the string.

The actual regex is pretty straightforward. We simply match the appropriate amount of stuff before the first semicolon and then use Retina's `*` replacement syntax to put in the correct number of spaces.

```
; |;$

```

This stage is applied after the last one to remove semicolons and spaces at the end of words that we changed to vertical.

# Answer
> 2 votes
# Retina 0.8.2, 58 bytes

```
(?<!^(\S* \S* )*\S*)
¶
¶?

+`(..(.)*¶)((?<-2> )*\S)
$1 $3

```

Try it online! Link includes test cases. Alternative solution, also 58 bytes:

```
( \S*)
$1¶
+` (.)
¶$1
 ¶

+`(..(.)*¶)((?<-2> )*\S)
$1 $3

```

Try it online! Link includes test cases.

I'm deliberately not using Retina 1 here, so I don't get operations on alternate words for free; instead I have two approaches. The first approach splits on all letters in alternate words by counting preceding spaces, while the second approach replaces alternate spaces with newlines and then uses the remaining spaces to help it split alternate words into letters. Each approach has to then join the last vertical letter with the next horizontal word, although the code is different because they split the words in different ways. The final stage of both approaches then pads each line until its first non-space character is aligned under the last character of the previous line.

Note that I don't assume that words are just letters because I don't have to.

# Answer
> 2 votes
## T-SQL, 289 bytes

```
DECLARE @ VARCHAR(MAX)='a a',@I INT=1,@S INT=0,@B INT=0WHILE @I<=LEN(@)IF SUBSTRING(@,@I,1)=''IF @B=0SELECT @S-=1,@=STUFF(@,@I,1,'
'+SPACE(@S)),@I+=@S+3,@B=1 ELSE SELECT @=STUFF(@,@I,1,''),@S+=1,@B=\ELSE IF @B=0SELECT @I+=1,@S+=1 ELSE SELECT @=STUFF(@,@I,0,'
'+SPACE(@S)),@I+=@S+3PRINT @

```

This runs on SQL Server 2016 and other versions.

@ holds the space-delimited list. @I tracks the index position in the string. @S tracks the total number of spaces to indent from the left. @B tracks which axis the string is aligned with at point @I.

The byte count includes the minimal example list. The script goes through the list, character by character, and changes the string so that it will display according to the requirements. When the end of the string is reached, the string is PRINTed.

# Answer
> 2 votes
## J, ~~35~~ 33 bytes

```
3 :'[;.0>(,|:)&:,.&.>/_98{.;:|.y'

```

This is a verb that takes the input as a single string with the words separated by spaces. For example, you could call it like this:

```
3 :'[;.0>(,|:)&:,.&.>/_98{.;:|.y' 'programming puzzles and code golf'

```

The output is a matrix of letters and spaces, which the interpreter outputs with newlines as required. Each line will be padded with spaces so they have the exact same length.

There's one slight problem with the code: it won't work if the input has more than 98 words. If you want to allow a longer input, replace the `_98` in the code by `_998` to allow up to 998 words, etc.

---

Let me explain how this works through some examples.

Suppose we have a matrix of letters and spaces that we imagine is a partial output for some words, starting with a horizontal word.

```
   [m=: 3 3$'vwx  y  z'
vwx
  y
  z

```

How could we prepend a new word before this, vertically? It's not hard: just turn the new word to a single-column matrix of letters with the verb `,.`, then append the output to that single-column matrix. (The verb `,.` is convenient because it behaves as an identity function if you apply it to a matrix, which we use for golfing.)

```
   (,.'cat') , m
c
a
t
vwx
  y
  z

```

Now we can't just iterate this way of prepending a word as is, because then we'd only get vertical words. But if we transpose the output matrix between each step, then every other word will be horizontal.

```
   (,.'dog') , |: (,.'cat') , m
d
o
g
catv
   w
   xyz

```

So our first attempt for a solution is to put each word into a single-column matrix, then fold these by appending and transposing between them.

```
   > (,|:)&.>/ ,.&.>;: 'car house dog children'
c
a
r
housed
     o
     g
     children

```

But there's a big problem with this. This puts the first letter of the next word before turning a right angle, but the specification requires turning before putting the first letter, so the output should be something like this instead:

```
c
a
rhouse
     d
     o
     gchildren

```

The way we achieve this is to reverse the entire input string, as in

```
nerdlihc god esuoh rac

```

then use the above procedure to build the zig-zag but turning only after the first letter of each word:

```
n
e
r
d
l
i
h
c
gode
   s
   u
   o
   h
   rac

```

Then flip the output:

```
   [;.0> (,|:)&.>/ ,.&.>;:|. 'car house dog children'
car
  h
  o
  u
  s
  edog
     c
     h
     i
     l
     d
     r
     e
     n

```

But now we have yet another problem. If the input has an odd number of words, then the output will have the first word vertical, whereas the specification says that the first word must be horizontal. To fix this, my solution pads the list of words to exactly 98 words, appending empty words, since that doesn't change the output.

# Answer
> 2 votes
# PowerShell, ~~101 89~~ 83 bytes

-12 bytes thanks to mazzy.

```
$args|%{$l+=if(++$i%2){$_.length-1;$t+=$_}else{1;$_|% t*y|%{$t+='
'+' '*$l+$_}}};$t

```

Try it online!

# Answer
> 2 votes
# , 126 bytes

```
function(x,`>`=strrep)for(i in seq(x)){H=i%%2;cat(paste0('
'>!H,' '>F*!H,e<-'if'(H,x,strsplit(x,''))[[i]]))
F=F+nchar(e[1])-H}

```

Try it online!

* -3 bytes thanks to @Giuseppe

# Answer
> 2 votes
# PowerShell, ~~74~~ 65 bytes

```
-join($args|%{$_|% t*y|%{($p+=(' ','
')[!$p]*!$i)*$i;$_};$i=!$i})

```

Try it online!

# Answer
> 1 votes
# JavaScript (Node.js), 75 bytes

```
a=>a.map(x=>i++&1?[,...x].join(`
`.padEnd(n)):(n+=x.length,x),n=i=0).join``

```

Try it online!

### Explanation and ungolfed

```
function f(a) {                   // Main function:
 return a.map(                    //  Map through all words:
  function(x) {
   if (i++ & 1)                   //   If i % 2 == 1 (i.e. vertical):
    return [,...x].join(          //    Since the first one needs to have its own linefeed
                                  //    and indentation, add a dummy item to the start.
     "\n".padEnd(n)               //    Join the array with the padded line feeds.
    );
   else {                         //   If i % 2 == 0 (i.e. horizontal):
    n += x.length;                //    Add the length of this string to the variable that
                                  //    counts how long the padded line feeds should be.
    return x;                     //    Append the string at the end without line feeds.
   }
  },
  n = i = 0                       //   Initialize variables.
                                  //   n: the length of the padded line feeds
                                  //      (including the line feed)
                                  //   i: keeps track of the direction
 ).join("")                       //  Join all stuffs and return.
}

```

# Answer
> 1 votes
# Stax, 12 bytes

```
ìZΣFτëWº═φ‼R

```

Run and debug it

# Answer
> 1 votes
# C (gcc), 93 87 bytes

Thanks to gastropner for the suggestions.

This version takes an array of strings terminated by a NULL pointer.

```
c,d;f(s,t)char**s,*t;{for(c=d=0;t=*s++;d=!d)for(;*t;c+=!d)printf("\n%*c"+!d,d*c,*t++);}

```

Try it online!

# Answer
> 1 votes
# Jelly, 21 bytes

```
Ẉm2Ä’x2Ż⁶xⱮṛ;⁷ɗ;ⱮY¥ƭ"

```

Try it online!

A full program taking the input as a list of strings and implicitly outputting to stdout the word ladder.

# Answer
> 1 votes
# Brain-Flak, 152 bytes

```
<>([()])<>{<>({}<>{()<({}<>)><>}<>)<>{}{<>({}<((()()()()()){})>)({<({}[()]<((((()()()()){}){}){})>)>()}{})<>(({}<>({}))[({}[{}])])<>}{}}<>{}{({}<>)<>}<>

```

Try it online!

I suspect this can be shorter by combining the two loops for odd and even words.

# Answer
> 1 votes
# \[ bash + stty \], 155 bytes

This does not trump @Rich solution but with more work it might be good. I realise it has an error atm (direction of new word) but since I don't have the reputation to comment on Rich's solution I have added this new answer even with an error to show another approach. It also does not suffer from a problem with whether at bottom of screen or not.

It wont work with TIO either ("not a possible ioctl" error).

```
j=0;for s;do
l=${#s};stty -onlcr
if((j%2==0));then
printf "%s\n\b" $s;else
for((i=0;i<$l;i++));do
printf "%s\n\b" ${s:$i:1}
done;fi;((j+=1));done;stty onlcr

```

Code that does work is:

```
j=0;for s;do l=${#s};stty -onlcr
if !((j%2));then
F=%s
f=$s
else
for((i=0;i<$l;i++));do
F=$F\\n\\b%s
f=$f\ ${s:$i:1}
done
fi
printf $F $f
f=;F=
((j+=1))
done
stty onlcr

```

Not so good as @Rich but 168 bytes. Could be cheeky and remove initialisation to save 4 bytes but that I feel is cheating.

# Answer
> 1 votes
# Python 3, 218 bytes

```

words=input().split();space=-1;
for i in range(len(words)):
 if i%2==0:
  print(words[i]);space+=len(words[i])
 else:
  for ch in words[i][:-1]:
   print(" "*(space)+ch)
  print(" "*(space)+words[i][-1],end="")

```

Try it online!

218 bytes i need to learn to reduce it ...

---
Tags: code-golf, ascii-art
---


title: Leading and Suffering Numbers

text:
# Question
Title: Leading and Suffering Numbers
## Introduction:

In Dutch, the words leading and suffering, being 'leiden' and 'lijden' respectively, are pronounced the same way. One is written with a "short ei", and one with a "long ij", as we Dutchman would say, but both 'ei' and 'ij' are pronounced \[ɛi\].

## Challenge:

Given a list of numbers, determine which (if any) are leading, and which (if any) are suffering.

A leading number is:

* A positive number
* Has at least four digits
* Is in the highest 50% of the list in terms of value
* Is still in the highest 50% of the list in terms of value, if it's 3rd digit is replaced with its 2nd digit, and it's 2nd digit-position is filled with a 0 (i.e. `1234` would become `1024`)

A suffering number is:

* A negative number
* Has at least four digits
* Is in the lowest 50% of the list in terms of value
* Is still in the lowest 50% of the list in terms of value, if it's 3rd digit is replaced with its 2nd digit, and it's 2nd digit-position is filled with a 0 (i.e. `-4321` would become `-4031`)

**Example:**

Input: `[5827, 281993, 3918, 3854, -32781, -2739, 37819, 0, 37298, -389]`
Output: leading: `[5827, 281993, 37819, 37298]`; suffering: `[-32781, -2739]`

*Explanation:*

If we sort and split the numbers into two halves, it would be:

```
[[-32781, -2739, -389, 0, 3798], [3854, 3918, 5827, 37819, 281993]]

```

There are only two negative numbers with at least four digits: `[-32781, -2739]`. Changing the digits as described above wouldn't change their position, so they are both suffering numbers.
For the largest halve, all the numbers have at least four digits: `[3854, 3918, 5827, 37819, 281993]`. Changing the digits as described above would change some of their positions however. The `3854` would become `3084`, putting it below `3798` which is in the lowest 50%, so `3854` is not a leading number in this list. The same applies to `3918` which would become `3098`, also putting it below `3798`. The other three numbers are leading, as `5827` which would become `5087`, which is still above `3798` and is in fact still at the same index of the sorted list. So `[5827, 37819, 281993]` are the leading numbers.

## Challenge rules:

* I/O is flexible. Input-list can be a list of integers, 2D digit lists, list of strings, etc. Output can be a list of lists of integers, two separated lists, two strings, both printed to STDOUT, etc.
* When determining if a number is leading/suffering, we only look at its new position of that number if only its digits are changed accordingly, not after we've applied the modifications to all numbers.
* We output the original numbers, not the modified ones.
* The numbers in the leading and suffering output-lists can be in any order.
* If the size of the input-list is odd, the number at the center doesn't belong to either halve.
* Numbers are guaranteed to remain unique after its modification. So a list like `[0, 1, 1045, 1485]` isn't a valid input-list, since `1485` would be equal to `1045` after it's modification.

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code (i.e. TIO).
* Also, adding an explanation for your answer is highly recommended.

## Test cases:

```
Input: [5827, 281993, 3918, 3854, -32781, -2739, 37819, 0, 37298, -389]
Output: leading: [5827, 281993, 37819, 37298]; suffering: [-32781, -2739]

Input: [-100, 472, 413, -1782]
Output: leading: []; suffering: [-1782]

Input: [-1234, -1235, -1236, 1234, 1235, 1236]
Output: leading: [1234, 1235, 1236]; suffering: [-1234, -1235, -1236]

Input: [-1919, -1819, -1719, -1619, -1500, -1444, 40, 4444, 18]
Output: leading: [4444]; suffering: []

Input: [-1004, -1111, -1000]
Output: leading: []; suffering: [-1111]

Input: [-1004, -1111, -1010, 1000]
Output: leading: [1000]; suffering: [-1111]

Input: [1000, -1000]
Output: leading: [1000]; suffering: [-1000]

Input: [1000, -5000, 4000]
Output: leading: [4000]; suffering: [-5000]

```

# Answer
> 6 votes
# 05AB1E, ~~27~~ ~~24~~ ~~23~~ ~~22~~ 21 bytes

```
(‚εÅmyεD1è0šāǝ}‹y*₄@Ï

```

Try it online!

# Answer
> 5 votes
# Python 2, ~~119~~ ~~118~~ ~~111~~ 107 bytes

```
lambda a:[[n for n in a if sorted(a)[::d][~len(a)/2]*d<int('0'.join(`n*d`[:2])+`n*d`[3:])>999]for d in-1,1]

```

Try it online!

Outputs as `suffering, leading`.

# Answer
> 2 votes
# Jelly, 30 bytes

```
,NµD2ị;0Ʋ2,3¦ḌƊ>ẠɗƇÆṁ;999Ɗ)N2¦

```

Try it online!

Given the length of Grimy’s 05AB1E answer, I’m sure this can be golfed better, but here it is.

# Answer
> 1 votes
# JavaScript (Node.js), 162 bytes

```
a=>[(g=i=>a.filter(n=>n*i>999&(h=t=>a.reduce((a,c)=>a+(c!=n&i*c<i*t(n)),0)>=a.length/2)(x=>x)&h(m=x=>x<0?-m(-x):x>999?m(x/10)*10+x%10:x-x%100+x/10%10)))(1),g(-1)]

```

Try it online!

Anonymous function that take an array of numbers as input and outputs a 2-element array as output. The first element in the output array is an array of leading numbers, the second element in the output array is an array of following numbers.

```
// a: input array of numbers
a=>
  // begin output array
  [
    // define a function g with input i
    // when i is 1, generate leading
    // when i is -1, generate following
    (g=i=>
      // function g returns a subset of a,
      // use filter() to select elements
      a.filter(n=>
        // n must be 4 digits and explicitly
        // positive or negative depending
        // on whether we are calculating
        // leading or following numbers
        n*i>999&
        // function h determines whether
        // the current number is in the
        // larger or smaller half,
        // depending on whether we are
        // calculating the leading or
        // following numbers.
        // argument t defines a
        // transformation that should
        // be applied to th current number
        (h=t=>
          // use reduce() to count the
          // number of numbers greater or
          // less than the transformed
          // current number
          a.reduce((a,c)=>
            // add the current total to...
            a+
            // either 0 or 1 depending on
            // whether the transformed
            // current number is in the
            // opposite group (leading vs
            // following
            (c!=n&i*c<i*t(n)),0)>=
          // are at least half in the
          // opposite group?
          a.length/2)
          // invoke h with the identity
          // transform
          (x=>x)&
          // invoke h again with a
          // transform m that moves the
          // 2nd digit to the 3rd digit and
          // 0's out the 2nd digit.
          // input for m is number x
          h(m=x=>
            // is x negative?
            x<0
              // invoke m with negated input
              // to force it to a positive value
              // and negate the result to
              // convert back to negative
              ?-m(-x)
              // otherwise, does x have 4 or
              // more digits?
              :x>999
                // recursively call m with 1
                // fewer digit, then add digit
                // back to the result
                ?m(x/10)*10+x%10
                // 3 or fewer digits, move
                // the 2nd digit to the 3rd
                // and 0 put the 2nd digit
                :x-x%100+x/10%10
        )
      )
    )
    // invoke g with input 1 for leading
    (1),
    // invoke g with input -1 for following
    g(-1)
  ]

```

---
Tags: code-golf, number, integer, permutations
---


title: Gravitational Force Between Numbers

text:
# Question
Title: Gravitational Force Between Numbers
The gravitational force is a force that attracts any two objects with mass. In this challenge our objects will be Numbers and their mass will be their value. To do so, we don't care about the strength of the force but the direction of it.

Imagine this set of numbers

```
[1 6 9 4 6 9 7 6 4 4 9 8 7]

```

Each of them creates a force between itself and it's adjacent numbers. Under some conditions, this will cause another number to be attracted (moved) toward a number. When the number is bigger than the adjacent, it attracts it. Lets take a look at our previous example:

```
[1 → 6 → 9 ← 4 6 → 9 ← 7 ← 6 ← 4 4 → 9 ← 8 ← 7]

```

The number `1` is not big enough to move `6`, but the number `6` is, etc... Basically, numbers are moved to the biggest adjacent number (also bigger than the number itself). If both of the adjacent numbers are equal it is not attracted then. It also happens when the number and it adjacent are equal.

This is only to show the attraction, but what happens after? Numbers that collide due to attraction are summed up:

```
[20 32 28]

```

So basically the challenge is, Given a set of numbers, output the result of the attracted set of numbers.

---

**Example 1**

```
Input  => [10 15 20 10 20 10 10]
          [10 → 15 → 20 10 20 ← 10 10]
Output => [45 10 30 10]

```

**Example 2**

```
Input  => [9 9 9 9 8 1 8]
          [9 9 9 9 ← 8 1 8]
Output => [9 9 9 17 1 8]

```

**Example 3**

```
Input  => [1 6 9 4 6 9 7 6 4 4 9 8 7]
          [1 → 6 → 9 ← 4 6 → 9 ← 7 ← 6 ← 4 4 → 9 ← 8 ← 7]
Output => [20 32 28]

```

**Example 4**

```
Input  => [1 2 3 2 1]
          [1 → 2 → 3 ← 2 ← 1]
Output => [9]

```

**Example 5**

```
Input  => [1]
Output => [1]

```

**Example 6**

```
Input  => [1 1]
Output => [1 1]

```

**Example 7**

```
Input  => [2 1 4]
Output => [2 5]

```

---

## Notes

* Attraction only happens once
* Numbers are not attracted to non-adjacent Numbers
* The set of numbers will only contain positive integers

# Answer
> 15 votes
# JavaScript (ES6),  ~~106 104~~  100 bytes

*Saved 2 bytes thanks to @Shaggy*

```
a=>a.filter(n=>n,[...a].map((v,i)=>a[a[p>v&(n=~~a[i+1])<p?k:i+(k=i,n>v&p<n)]+=x=a[i],p=v,i]-=x,p=0))

```

Try it online!

### Commented

We first update the original input array `a[]` by iterating on a copy of it. During this step, all values 'attracted' by other ones are set to \\$0\\$.

Because the array is parsed from left to right, we can just add \\$a\_i\\$ to \\$a\_{i+1}\\$ whenever a value is attracted by its right neighbor.

Example: \\$4\rightarrow5\rightarrow6\\$ is turned into \\$\[0,\color{red}9,6\]\\$ and then \\$\[0,0,\color{red}{15}\]\\$.

But when several values in a row are attracted by their left neighbor, we need to add \\$a\_i\\$ to the first attractor \\$a\_k\\$ of this sequence (with \\$k\<i\\$) rather than simply \\$a\_{i-1}\\$.

Example: \\$6\leftarrow5\leftarrow4\\$ is turned into \\$\[\color{red}{11},0,4\]\\$ and then \\$\[\color{red}{15},0,0\]\\$.

```
[...a]                 // create a copy of a[]
.map((v, i) =>         // for each value v in a[] at position i:
  a[                   //   this statement updates a[i]:
    a[                 //     this statement updates either a[i] or an adjacent value:
      p > v &          //       if the previous value p is greater than v
      (n = ~~a[i + 1]) //       and the next value n
      < p ?            //       is less than p (attraction to the left):
        k              //         use k (k is initially undefined, but this code cannot
                       //         be triggered during the first iteration)
      :                //       else:
        i + (          //         use either i or i + 1:
          k = i,       //           set k to i
          n > v &      //           use i + 1 if n is greater than v
          p < n        //           and p is less than n (attraction to the right)
        )              //
    ] += x = a[i],     //     add x = a[i] to the entry defined above
    p = v,             //     update the previous value to v
    i                  //     actual index to update a[i]
  ] -= x,              //   subtract x from a[i]
  p = 0                //   start with p = 0
)                      // end of map()

```

We then filter out all entries equal to \\$0\\$.

```
a.filter(n => n)

```

# Answer
> 9 votes
# Stax, ~~27~~ ~~25~~ ~~23~~ 18 bytes

```
«╥╦.ê§┘h!@ÆEÿ☺╜╫♥B

```

Run and debug it

Output is separated by newlines.

This program operates on adjacent pairs in the array, and determines whether there should be a split between them using this procedure.

Consider some arbitrary input `[... w x y z ...]`. Here is how to determine if there should be a split between `x` and `y`.

* If `x == y`, then yes.
* If `x > y`, then iff `z >= x`.
* If `y > x`, then iff `w >= y`.

The summing is left as an exercise.

# Answer
> 8 votes
# Retina 0.8.2, 64 bytes

```
\d+
$*
(?<=(1+)) ((?=(1+\1))(?<!\3 \1 )|(?!\1)(?!1+ \1))

1+
$.&

```

Try it online! Link includes test suite. Explanation:

```
\d+
$*

```

Convert to unary.

```
(?<=(1+)) ((?=(1+\1))(?<!\3 \1 )|(?!\1)(?!1+ \1))

```

Remove the separators between attracted numbers. `(?<=(1+))` sets `\1` to the number before the separator. After the separator, there are then two cases:

* The number after the separator is greater than both of the numbers before the separator
* The number before the the separator is greater than both of the numbers after the separator

In these cases there is an attraction between the two numbers and deleting the separator causes the numbers to collide, adding them together.

```
1+
$.&

```

Convert to decimal.

# Answer
> 6 votes
# Jelly, 23 bytes

```
Ø0jMÆmær0Ʋ3Ƥ×=4$o<ʋƝk⁸§

```

Try it online!

A monadic link which takes a list of integers as its argument and returns a list of integers.

### Explanation

```
Ø0j                     | Join [0, 0] with input list
         Ʋ3Ƥ            | For each length 3 infix, do the following as a monad:
   M                    | - Indices of maximum
    Æm                  | - Mean
      ær0               | - Round to even (so the means of [1, 2, 3], [1, 2], [2, 3] and [1, 3] will all round to 2
                  ʋƝ    | For each neighbouring pair, do the following as a dyad:
            ×           | - Multiply
             =4$        | - Check if equal to 4
                o       | - Or
                 <      | - First number less than second
                    k⁸  | Split input after truthy values of the above
                      § | Sum, vectorised

```

Some inspiration taken from @recursive’s Stax answer.

# Answer
> 4 votes
# C (gcc), 111 bytes

```
a,b,c,s;P(){s=!printf("%d ",s);}f(int*v){for(b=s=0,c=*v;a=b,b=c;a<b|b<a&c<a||P(),s+=b,b<c&c<=a|!c&&P())c=*++v;}

```

Try it online!

Takes a zero-terminated array of integers.

### Explanation

```
a,b,c,  // Three consecutive elements of input array
s;      // Accumulator for sum
P(){s=!printf("%d ",s);}  // Print and clear s
f(int*v){
    for(
        // Init
        b=s=0,
        c=*v;
        // Loop test
        a=b,  // Shift b into a
        b=c;  // Shift c into b, exit if zero
        // Post loop
        a<b|b<a&c<a||P(),  // Print if a==b || (b<a && a<=c)
        s+=b,  // Accumulate
        b<c&c<=a|!c&&P()   // Print if c==0 || (b<c && c<=a)
    )
        // Loop body
        c=*++v;  // Read next number into c
}

```

# Answer
> 3 votes
# Python 2, 162 bytes

```
l=input()
a=[(L<R>C)-(R<L>C)for L,C,R in zip([0]+l,l,l[1:]+[0])]
while any(a):
 i=0
 while a[i]==0:i+=1
 m=a.pop(i);x,y=[i,i+m][::m];l[x:y+1]=l[i]+l[i+m],
print l

```

Try it online!

# Answer
> 3 votes
# , 45 bytes

```
+//.~0,[:+/\2(<+.1=*)/\3(>./1:/@I.@E.])\0,,&0

```

Try it online!

Inspired by recursive's original Stax answer

# Answer
> 3 votes
# , ~~222~~ ~~196~~ 173 bytes

Here is a solution with some help from Robin Ryder

```
n=length(d<-diff(y<-x<-scan()));l=c(1,sign(d[-n]+d[-1]),-1);m=!!l*n&c(d[1]>0,d[-1]>0|d[-n]<0,d[n]<0);for(t in 1:n){for(i in which(m))y[a]=y[a<-i+l[i]]+x[i];y=x=y-x*m};x[!m]

```

Try it online!

A short set of comments

```
n=length(d<-diff(y<-x<-scan()));  #read input and compute pairwise differences
                    #d[-n]+d[-1]: compare left and right differences
l=c(1,sign(d[-n]+d[-1]),-1)                 #direction of attraction
m=!!l*n&                          #indices of attracted numbers
  c(d[1]>0,d[-1]>0|d[-n]<0,d[n]<0)
                                   #!!l*n eliminates zeroes in l & the case n==0
for(t in 1:n){                   #excessive loop on transfers
 for(i in which(m))
   y[a]=y[a<-i+l[i]]+x[i]         #transfer right vs. left
 y=x=y-m*x}                        #complete transfer
x[!m]                             #output

```

# Answer
> 3 votes
## Python, ~~114~~ 112 bytes

```
lambda a:eval('['+'+'.join(str(c)+',0'*((e<c>d)==(c<d>b))for b,c,d,e in zip([0]+a,a,a[1:]+[0],a[2:]+[0,0]))+']')

```

This uses the fact that the direction of the arrow doesn't actually matter, and that the presence of an arrow between a\[i\] and a\[i+1\] can be determined by looking at the range of four elements a\[i-1:i+3\].

Edit: Thank you to Jo King for the rule clarification

# Answer
> 2 votes
# Perl 5, ~~156~~ 147 bytes

```
$q='$F[$i';map{eval"\$i++while$q]$_"}"<$q+1]",">$q+1]&&$q]>$q+2]&&\$i<\@F"if eval"$q-1]-$q+1]||$q]>$q+1]";$\.=$".sum@F[$p..$i];($p=++$i)<@F&&redo}{

```

Try it online!

# Answer
> 2 votes
# K (ngn/k), 47 bytes

```
{+/'x@.={x x}/(!#x)+{-/2=+/x<\:x 2 0}'3':0,x,0}

```

Try it online!

`0,x,0` surround the argument with 0s

`3':` triplets of consecutive items

`{` `}'` for each do

`x 2 0` get last and first of the current triplet - `x[2]` and `x[0]`. they are the neighbours of `x[1]`, on which the triplet is centred

`x<\:` compare using less-than against each of the current triplet

`+/` sum. the result is a pair corresponding to `x[2]` and `x[0]`

`2=` check if either neighbour is greater than the other 2 elements from `x`, return a pair of 0-or-1 booleans

`-/` subtract them. a result of -1 means `x[1]` is attracted to the left, 1 to the right, and 0 means it stays in place

`(!#x)+` add 0 to the first item, 1 to the second, etc. this computes the indices towards which items are attracted

`{x x}/` index with itself until convergence. the result are the effective indices to which each item is ultimately attracted

`x@.=` group `x` (the original argument) by those. the result is a list of lists

`+/'` sum each

# Answer
> 2 votes
# Clojure, ~~299~~ 252 bytes

```
(fn[l](loop[o[0]m(vec(map-indexed(fn[i v](def f #(max(nth l(+ % i)0)v))(-(f -1)(f 1)))l))i 0](defn f[x](update o(-(count o)x)#(+(l i)%)))(cond(<=(count m)i)(pop o)(>(m i)0)(recur(f 2)m(inc i))(<(m i)0)(recur(f 1)m(inc i))1(recur(conj(f 1)0)m(inc i)))))

```

Try it online!

---

### Explanation:

```
(fn [l]
  (loop [o [0]
         m (vec(map-indexed (fn [i v] ; This maps each element l[i] of l to max(l[i-1], l[i]) - max(l[i+1], l[i])
                              (def f #(max (nth l (+ % i) 0) v))
                              (- (f -1) (f 1)))
                            l))       ; l[x] is zero when l[x] is out of bounds of the input vector l
         i 0]
    (defn f [x] (update o (- (count o) x) #(+ (l i) %)))
    ; Defines a function f(x) that returns the result of mapping the (x-1)th to last element of o over the function g(y) = l[i] + y

    (cond
      (<= (count m) i) (pop o) ; If the length of m is less than or equal to i, there are no more elements in m, so return all but the last element of o
      (> (m i) 0) (recur (f 2) m (inc i)) ; If m[i] is positive, l[i] is pulled toward to the previous element, so add l[i] to the 2nd to last element of o
      (< (m i) 0) (recur (f 1) m (inc i)) ; If m[i] is negative, l[i] is pulled toward the next element, so add l[i] to the last element of o
      1 (recur (conj (f 1) 0) m (inc i))))) ; 1 is truthy
      ; If the length of l is less than or equal to i, and m[i] is not positive or negative, we have m[i] = 0, so l[i] is not pulled toward any other element

```

# Answer
> 1 votes
# APL (Dyalog Classic), ~~52~~ 51 bytes

```
{+/(⊃∘⍵¨⊢)⌸{⍵[⍵]}⍣≡(⍳≢⍵)+{-/2=+⌿⍵∘.<1↓1⌽⍵}¨3,/∊0⍵0}

```

Try it online!

translation of my k answer

# Answer
> 1 votes
# 05AB1E, 21 bytes

```
0.øŒ3ùεZQXsÂU‚ÆZ≠}Å¡O

```

Try it online!

---
Tags: code-golf
---


title: Code golf: Distributing the balls (I)

text:
# Question
Title: Code golf: Distributing the balls (I)
## Challenge

> In this task you have compute the number of ways we can distribute A balls into B cells with with every cell having at-least one ball.

The inputs A and B are given in a single line separated by a blank,the inputs are terminated by EOF.

You may like to check your solutions here.

**Input**

```
0 0
1 0
12 4
6 3
18 17
20 19
15 13
18 9
20 20
17 14
9 2
14 13
18 11

```

**Output**

```
1
0
14676024
540
54420176498688000
23112569077678080000
28332944640000
38528927611574400
2432902008176640000
21785854970880000
510
566658892800
334942064711654400

```

**Constraints**

* **Every A and B can be distinguishable.**
* 0 \<= A,B \<= 20
* You can use any language of your choice
* Shortest solution wins!

# Answer
> 4 votes
## JavaScript (90 93)

```
function f(a,b){n=m=r=1;for(i=b;i>0;n*=-1){r+=n*m*Math.pow(i,a);m=m*i/(b-i--+1)}return--r}

```

http://jsfiddle.net/RDGUn/2/

Obviously, any math-based language such as APL will beat me because of syntax verbosity and lack of built-in mathematical constructs :)

**Edit** Also, I don't have any input-related functionality except parameters passed into the function, not sure how to use standard input with JavaScript...

**Edit:** Move `i--` into `m=m*` expression; move `n*=-1` into `for`; start `r=1` to combine assignments and remove extraneous one on return. (save 3 chars)

# Answer
> 4 votes
### Golfscript - 56 50 49 48 41 40 38 37 chars

```
n%{~),{!}%\{0.@{.@+2$*@)@}/;;]}*)p;}/

```

Note: this handles multiple lines of input, is fast (1/8 secs to do the test cases), and doesn't break for any legal input.

(The first version was also my first ever Golfscript program; thanks to eBusiness for pointing out several tricks I missed).

In order to make this a useful educational post too, here's an explanation of how it works. We start with the recurrence `f(n, k) = k * (f(n-1, k) + f(n-1, k-1))`. This can be understood combinatorically as saying that to place `n` distinguishable balls in `k` distinguishable buckets such that each bucket contains at least one ball, you pick one of the `k` buckets for the first ball (`k *`) and then either it will contain at least one more ball (`f(n-1, k)`) or it won't (`f(n-1, k-1)`).

The values resulting from this form a grid; taking `n` as the row index and `k` as the column index and indexing both from 0 it starts

```
1   0   0   0    0    0   0 ...
0   1   0   0    0    0   0 ...
0   1   2   0    0    0   0 ...
0   1   6   6    0    0   0 ...
0   1  14  36   24    0   0 ...
0   1  30 150  240  120   0 ...
0   1  62 540 1560 1800 720 ...
.   .   .   .    .    .   . .
.   .   .   .    .    .   .  .
.   .   .   .    .    .   .   .

```

So turning to the program,

```
n%{~ <<STUFF>> }/

```

splits the input into lines and then for each line evaluates it, putting `n` and `k` on the stack, and then calls `<<STUFF>>`, which is as follows:

```
),{!}%\{0.@{.@+2$*@)@}/;;]}*)p;

```

This computes the first `k+1` entries of the `n+1`th row of that grid. Initially the stack is `n k`.
`),` gives stack of `n [0 1 2 ... k]`
`{!}%` gives stack of `n [1 0 0 ... 0]` where there are `k` 0s.
`\{ <<MORE STUFF>> }*` brings the `n` to the top and makes it the number of times we execute `<<MORE STUFF>>`.
Our stack currently is a row of the table: `[f(i,0) f(i,1) ... f(i,k)]`
`0.@` puts a couple of 0s before that array. The first one will be `j` and the second one will be `f(i,j-1)`.
`{ <<FINAL LOOP>> }/` loops through the elements of the array; for each one it puts it on top of the stack and then executes the loop body.
`.@+2$*@)@` is boring stack manipulation to take `... j f(i,j-1) f(i,j)` and yield `... j*(f(i,j-1)+f(i,j)) j+1 f(i,j)`
`;;]` pops off the left-over `k+1 f(i,k)` and gathers everything into an array, ready for the next go round the loop.
Finally, when we've generated the `n`th row of the table,
`)p;` takes the last element, prints it, and discards the rest of the row.

For posterity, three 38-char solutions on this principle:
`n%{~),{!}%\{0.@{.@+@.@*\)@}/;;]}*)p;}/`
`n%{~),{!}%\{0:x\{x\:x+1$*\)}/;]}*)p;}/`
`n%{~),{!}%\{0.@{@1$+2$*\@)}/;;]}*)p;}/`

# Answer
> 3 votes
## Golfscript - 26 chars

Warning: The 12 4 case needs a lot of memory (although not as much as the answer below) and takes a quite a while to run

```
~:)\?:x,{x+)base(;.&,)=},,

```

---

Obviously this answer has some problems, but I will leave it here because the comments refer to it and mellamokb's answer is based off it.

**Golfscript - 24 chars**

Warning: The 12 4 case needs a lot of memory and takes a quite a while to run

```
~:o)\?,{o)base[0]-,o=},,

```

# Answer
> 3 votes
# GolfScript - 45 38 36 characters

### Medium-force dirty implementation recurrence relation (38 36 characters):

```
n%{~{.2$*{\(.2$f\2$(f+*}{=}if}:f~p}/

```

The recurrence relation I stole from Peter Taylors solution, it goes like this:

`f(x, y) = y * ( f(x-1, y) + f(x-1, y-1) )`

With special cases if either variable is 0.

My implementation does not reuse previous results, so each function call branch to two new calls, unless one of the zero cases have been reached. This give a worst case of 2^21-1 function calls which takes 30 seconds on my machine.

### Light-force series solution (45 characters):

```
n%{~.),0\{.4$?3$,@[>.,,]{1\{)*}/}//*\-}/p;;}/

```

# Answer
> 3 votes
## J, 40

```
4 :'|-/x(^~*y!~])i.1x+y'/&.".;._2(1!:1)3

```

E.g

```
4 :'-/((x^~|.@:>:)*y&(!~))i.y'/x:".>{.;:(1!:1)3
15 13
28332944640000

```

\<1sec for all test cases.

### Edits

* **(52 → 47)** Reduce with `-/` instead of alternating `(1 _1)*` (J-B's idea)
* **(47 → 53)** Noticed multiline input requirement :-/
* **(53 → 48)** Exploit symmetry of binomials.
* **(48 → 48)** Make tacit!
* **(48 → 41)**
* **(41 → 40)** Squeeze increment+conversion into `1x+`

# Answer
> 3 votes
## J, 38 to 42

Depending on your strictness preferences about interactive languages and output presentation, take your pick from the J spectre of solutions:

* **38** shortest interactive: `4 :'|-/(!&y*^&x)i.1x+y'/&".;._2(1!:1)3`
Launch jconsole, enter it, then paste the input (end with C-d). You'll notice the output is space-separated (J is a vector language, it performs the computation on the whole input as a whole and returns it as a 1D vector, whose default presentation is on a single line). I consider that ok, the spirit of this problem is computation, not presentation. But if you insist on having newlines instead:
* **39** longer interactive: `4 :'|-/(!&y*^&x)i.1x+y'/&.".;._2(1!:1)3`
Replacing *Compose* (`&`) with *Under* (`&.`) returns a vector of strings, whose presentation ends up on separate lines.
* **42** batch mode: `4 :'echo|-/(!&y*^&x)i.1x+y'/&".;._2(1!:1)3`
Run from the command line as `$ jconsole balls.ijs < balls.in`

If you voted this up, you might want to go give Eelvex's solution some credit as well.

# Answer
> 3 votes
## Common Lisp (83)

```
(defun b (x y)
  (if (= (* x y) 0)
      (if (= (+ x y) 0) 1 0)
      (* y (+ (b (decf x) y) (b x (1- y)))))))

```

It seems like there should be a shorter way to test the base cases, but nothing occurs to me offhand.

# Answer
> 2 votes
# J, 55 characters

```
(wd@(4 :'(y^x)--/(!&y*^&x)|.i.y')/@".@,&'x');._2(1!:1)3

```
* Passes current test cases. I *think* I understand the math...
* j602, console only (`wd`). Input on stdin, output on stdout.

Bash test script:

```
jconsole disballs.ijs <<END
12 4
6 3
END

```

# Answer
> 2 votes
### dc, 100 chars

```
[0q]s5[1q]s6[l2l3>5l3 0>5l2 0=6l2 1-S2l3dS3 1-S3l1xL3s9l1xL2s9+L3*]s1[?z0=5S3S2l1xL3L2+s9fs9l4x]ds4x

```

Alas, dc doesn't seem to be supported by ideone. There may be a character or two still to squeeze out, but it's bedtime.

Note: this supports multiple lines of input, has sufficient precision to give the correct output even for `20 19` (curse you, Perl, for the time I wasted debugging my solution!), and gives the correct output for `0 0`.

Suggestions from Nabb allow shortening at least as far as

```
[0q]sZ[1q]sI[?z0=ZSkSn[lnlk>Zlk0>Zln0=Iln1-SnlkdSk1-SklFxLks9lFxLns9+Lk*]dsFxfs9l4x]ds4x

```

at the cost of leaving junk in the register stacks (and thus running out of memory if we compute billions of answers).

# Answer
> 2 votes
**Python 140 Chars**

```
import sys
f=lambda n,k:(n and k and n>=k and k*(f(n-1,k-1)+f(n-1,k)))or(n+k==0 and 1)or 0
for l in sys.stdin:print f(*(map(int,l.split())))

```

# Answer
> 1 votes
## Golfscript (28 31 37)

`~):$\.($\?:@;?,{@+}%{$base$,\-[0]=},,`

Modification to `gnibbler`'s GolfScript solution. I think this is a working solution - tested with \[3,2\], \[4,2\], \[6,3\], and \[9,2\] with correct answers. (I used `$` and `@` for variables to tighten up space around the `base` keyword).

There are two problems with `gnibbler`'s current solution.

1. Checking length after removing \[0\] does not guarantee a solution, because \[1,1,1,1\] would be valid for input \[4,2\], even though all 4 balls are in the same cell (1). So I've modified to check also that all digits are used, i.e., the array contains 1-2, so each cell contains at least one ball.
2. In the case of input \[4,2\], the base-3 format of numbers 0-27 are less than 4 digits, and the left-most 0's are not included. That means \[1,1\] is included as a valid solution, even though it is technically actually \[0,0,1,1\], which means the first two balls are not placed anywhere. I fix by adding 3^3 to every entry (generically k^n-1 to the array of k^n entries) so that the first entries are shifted upward to having at least n-digits in base-k format, and the last entries will automatically be invalid anyway and won't affect the solution (because the second digit will always be 0).

**Edit**

`~:@\?:$,{$+}%{@base(;@,\-,0=},,`

```
`~:@\?:$,{$+@base(;@,\-,0=},,`

```

Better solution yet! No need to increment, just add to all of the numbers so they start with \[1\], and no digits will be missing (including the left-padding of 0's) once you decon that first digit. This solution should work and has been tested with same entries above. It's also a lot faster because we aren't incrementing before taking exponent to generate the array (but still suffers from same performance / memory problem for larger input).

**Edit**: Use `gnibbler`'s idea of moving the addition of `$` inside of the filter instead of as an extra step. (save 3 chars).

# Answer
> 1 votes
# 05AB1E, 19 bytes

```
#D`ULX.Œʒ€gßĀ}gs_P+

```

NOTE: It's extremely slow, and already times out for `12 4`. It is working as intended, though. ~~Will see if I can come up with an alternative method which works for all test cases in a reasonable time.~~ See below for a much faster version which runs all test cases in less than a second.

Try it online or verify a few more (of the smaller) test cases.

**Explanation:**

```
#               # Split the (implicit) input-string by spaces
 D              # Duplicate it
  `             # Push both values to the stack
   U            # Pop and store the second value in variable `X`
    L           # Create a list in the range [1,n] for the first value
     X.Œ        # Create a list of all possible ways to divide this list into `X` partitions
                # (including empty sublists, so we'll have to filter them out:)
        ʒ       # Filter this list of lists of partition-lists by:
         €g     #  Get the length of each partition-list
           ß    #  Get the minimum length
            Ā   #  Truthify; 0 remains 0 (falsey); anything else becomes 1 (truthy)
             }g # After the filter, take the length to get the amount left
 s              # Swap so the duplicated input-list is at the top of the stack again
  _             # Check for each value if they're equal to 0 (1 if truthy; 0 if falsey)
   P            # Take the product of the two to check if both input-values are 0
    +           # And add it to the earlier calculated product (edge case for [0,0] = 1)
                # (After which the result is output implicitly)

```

---

# 05AB1E, 29 bytes

Here a much faster version which works for all test cases in about 0.5 seconds on TIO:

```
Î#R`V©LRvyYmX*NÈ·<*+Xy*®y->÷U

```

Port of *@mellamokb*'s JavaScript answer, so make sure to upvote him!

Try it online or verify all test cases.

**Explanation:**

```
Î                    # Push (result=) 0 and the input
 #                   # Split the input by spaces
  R`                 # Push the values to the stack reversed
    V                # Pop and store the first value in variable `Y`
     ©               # Store the second value in variable `®` (without popping)
      LRv            # Loop `y` in the range [`®`,1], with index `N` in the range [0,`®`):
         yYm         #  Calculate `y` to the power `Y`
            X*       #  Multiply it by `X`
                     #  (Note: `X` is 1 before setting it to another value initially)
              NÈ     #  Check if index `N` is even (1 if truthy; 0 if falsey)
                ·<   #  Double it; and decrease it by 1 (1 if truthy; -1 if falseY0
                  *  #  Multiply it to the earlier number
                   + #  And add it to the result
         Xy*         #  Push `X` multiplied by `y`
         ®y->        #  Push `®` - `y` + 1
             ÷       #  Integer divide them
              U      #  Pop and store it as new variable `X`
                     # (output the result at the top of the stack implicitly after the loop)

```

NOTE: Works for edge case `0 0` in this case (unlike the JavaScript answer I ported this method from), because the `L` builtin will create a list `[0,1]`.

---
Tags: code-golf, math, combinatorics
---


# Question
Title: All possible ways to interleave two strings
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.

# Answer
# Pyth, 26

```
M?G?H++LhGgtGH+LhHgGtH]G]H

```

Try it here

This is a very basic implementation of the given recursive formula. It defines a function `g` that performs the required task. The link is a modified program that reads the strings from STDIN newline separated, to be more convenient. To call the function do `g<string1><string2>`.

### Expansion:

```
M                ##  Define a function g taking two arguments: G and H
 ?G?H ... ]G]H   ##  Two ternaries: if G is empty return a list containing H
                 ##  if H is empty return a list containing G
   +             ##  otherwise return these next two lists joined together
   +LhGgtGH      ##  the first letter of G added to each result of a recursive call to g
                 ##  with G missing its first character and H
   +LhHgGtH      ##  the same as above but with G and H swapped

```

The two recursive calls are very similar, but I haven't been able to find a way to golf them any more.
> 1 votes

# Answer
# Haskell, 47

```
(x:s)#b=(x:)<$>s%b
a#b=[]
[]%b=[b]
a%b=a#b++b#a

```

`%` is the operator that solves this challenge.

`#` is an operator that takes in two lists and finds all the ways to interleave them such that the first character is from the first string (with an edge case - if the first list is empty, then the result is an empty list) by recursing to `%`.

then, `%` works by just applying `#` twice.

**Edit:** The previous version had a bug in which `""%""` returned `["",""]`, so I fixed it up. It was fixed by adding a base case to `%`, which then allowed to remove a base case of the same length from `#` (which really, didn't make much sense).
> 11 votes

# Answer
## Haskell, ~~53~~ 48 bytes

```
a%""=[a]
a%b=[x:t|(x:y,z)<-[(a,b),(b,a)],t<-y%z]

```

Defines a function `%` for which `a%b` with strings `a,b` gives a list of strings.

Given two strings, we choose one of the two to take the first character from. We then recurse on the remainder of two strings, prepending that character to each result.

When one of the string is empty, the only possible result is the other string. `""%""=[""]` would also suffice, but's it's longer.

---

**53 bytes:**

```
a@(b:c)%d@(e:f)=((b:)<$>c%d)++((e:)<$>a%f)
a%d=[a++d]

```

Defines a function `%` for which `a%d` with strings `a,d` gives a list of strings.

The function is defined recursively. If we take a character from the first string, then it must be prepended to each result of the recursive call on the remained of the first string with the second string. Symmetrically for the other string.

For the base case, if one of the strings is empty, the result is a single-element list of their concatenation. This is shorter than two cases for each string being empty.
> 10 votes

# Answer
## Python 2, 71 bytes

```
f=lambda*p:[x[0]+t for x,y in p,p[::-1]for t in x and f(x[1:],y)]or['']

```

Example run:

```
>> f('ab','AB')
['abAB', 'aABb', 'aAbB', 'ABab', 'AabB', 'AaBb']

```

Given two strings `x,y` we can take the first character of `x` and prepend it to each result of the recursive call with it missing `f(x[1:],y)`. Or, we can do the same with `x` and `y` switched. By taking `x,y` as either the input `p` or its reversal \`p\[::-1\], we get both possibilities.

To avoid taking from an empty string `x`, we logical short-circuit with `x and`. If both strings are empty, neither string can be `x` and we get and empty list of possibilities, which we fix with `or` to the correct base case `['']`.

A similar generative strategy in Python 3 (73 bytes):

```
f=lambda p,s='':[f((x[1:],y),s+x[0])for x,y in[p,p[::-1]]if x]or print(s)

```
> 8 votes

# Answer
# Python, 80

As requested, here's a python answer:

```
f=lambda a,b,c='':[c+x for x in[a+b][a>''<b:]or f(a[1:],b,a[0])+f(a,b[1:],b[0])]

```

Thanks Sp3000 for eating 4 bytes :)
> 3 votes

# Answer
# CJam, 38

```
q~L{_2$e&{_2$(\@jf+@@(@@jf++}{+a}?}2jp

```

Try it online

Dynamic programming (using memoized recursion).

**Explanation:**

```
q~         read and evaluate the input (2 strings)
L{…}2j     calculate with memoized recursion with no initial cache and 2 arguments
  _2$      copy the 2 strings
  e&{…}    if they are both non-empty
    _2$    copy the strings again (they're in reverse order)
    (      take out the first character of the first string
    \@     move the strings after the character
    j      solve recursively
    f+     prepend the character to all results
    @@     bring the other copy of the strings on top (in order)
    (      take out the first character of the second string
    @@     move the strings after the character
    j      solve recursively
    f+     prepend the character to all results
    +      concatenate the 2 sets of results
  {…}      else
    +      concatenate the 2 strings (at least one is empty)
    a      put the result in an array
  ?        end if
p          pretty-print the results for the input strings

```
> 2 votes

# Answer
## JavaScript (Firefox 30-57), ~~88~~ ~~84~~ 81 bytes

```
(s,t,g=(v,w)=>v[1]?f(v.slice(1),w).map(x=>v[0]+x):[v+w])=>[...g(s,t),...g(t,s)]

```

Edit: Saved 4 bytes by improving my termination condition. Saved 3 bytes thanks to @edc65.
> 2 votes

# Answer
## CJam, 32 bytes

```
qN/_:,eeWf%e~e!\f{\{_2$=(ot}/No}

```

Test it here.

This feels really golfable, but so far I've only found 4 alternative solutions that all have the same byte count:

```
qN/_ee{),*~}%e!\f{\{_2$=(ot}/No}
l_:!l_0f>@+])e!\f{\{_2$=(ot}/No}
ll__3$:!+.=])e!\f{\{_2$=(ot}/No}
qN/[_:,2,]ze~e!\f{\{_2$=(ot}/No} (found by Sp3000)

```

The basic idea is to generate all permutations of `0`s and `1`s corresponding to which string to take each character in the result from. That's everything up to and including the `e!`. The rest simply pulls out characters in that order from the two strings then.
> 2 votes

# Answer
# Brachylog, 8 bytes

```
p~cᵐz₁cc

```

Try it online!

Takes input as a list of two strings through the input variable, and generates all possible interleavings through the output variable. Since the test cases seem to permit duplicate interleavings where there are shared letters, I haven't taken any care to avoid them, but this generates a *lot* more duplicates and not just with shared letters. (If this isn't allowed, but the shared letter duplicates aren't necessary, just add three bytes to wrap in `{}ᵘ` for output as a list with no duplicates.)

```
p           A permutation of
            the input variable
   ᵐ        with each element
 ~c         arbitrarily partitioned,
    z       zipped
     ₁      without cycling,
      cc    and concatenated twice
            is the output variable.

```

Essentially, this generates every partition of both strings, then interleaves them in the normal deterministic fashion in either order. The extra duplicate interleavings are due to partition pairs where the difference between the length of the first and the length of the second has some value other than 0 or 1, so that one of them has chunks that get concatenated to each other at the end. So, to produce output with the same multiplicities as the sample output:

# Brachylog, 17 bytes

```
p~cᵐ{lᵐ-ℕ<2&}z₁cc

```

Try it online!

The extra code, `{lᵐ-ℕ<2&}`, fails any partition pair where any extraneous divisions are made. (I altered the header on TIO to print with quotes for easier output checking in the Python shell.)
> 2 votes

# Answer
# MATL, ~~34~~ 30 bytes

```
h1Mgw~hY@Xu!ttYs*w~tYs1Gn+*+!)

```

This uses an idea from this answer: if the lenghts of the strings are `m` and `n`, enumerate all `m+n` bit patterns with `m` bits set. One way do that that enumeration is: generate all permutations of a vector with `m` ones and `n` zeros and then remove duplicates.

**Try it online!**

### Explanation

```
h     % implicitly input the two strings of lengths m and n. Concatenate
1M    % push the two strings again
g     % convert the second strings into ones
w~    % swap. Convert the second string into zeros
h     % concatenate: vector of zeros and ones
Y@    % 2D array with all permutations of that vector, each on a row
Xu    % remove duplicate rows
!     % transpose
ttYs  % duplicate twice. Cumulative sum along each column
*     % element-wise product. Produces, in each column, indices for
      % elements of the first string; 1, 2,...,m. The rest are 0
w~    % swap, negate
tYs   % duplicate. Cumulative sum along each column
1Gn+  % add length of first input
*     % element-wise product. Produces, in each column, indices for
      % elements of the second string: m+1,...,m+n. The rest are 0
+     % add. This gives indices into the concatenated string created initially
!     % transpose back
)     % index into concatenated string. Implicitly display

```
> 1 votes

# Answer
## Batch, ~~154~~ 152 bytes

```
@if "%~1%~2"=="" echo %3
@set t=%~1
@if not "%t%"=="" call %0 "%t:~1%" "%~2" %3%t:~,1%
@set t=%~2
@if not "%t%"=="" call %0 "%~1" "%t:~1%" %3%t:~,1%

```
> 0 votes

# Answer
# Ruby, 83 bytes

A recursive function that returns `[a+b]` if either of those strings are empty. Otherwise, it returns a list of strings `a[0] + every string in v[a[1..-1],b]` added to a list of string `b[0] + every string in v[a,b[1..-1]]`

```
v=->a,b{a[0]&&b[0]?v[a[1..-1],b].map{|i|a[0]+i}+v[a,b[1..-1]].map{|i|b[0]+i}:[a+b]}

```
> 0 votes

---
Tags: code-golf, string, permutations
---