
Weaving two arrays, keeping relative order - objectivem
http://mohit.athwani.net/backtracking/weaving-two-arrays/
======
jnordwick
That seems like an very complex way to frame the problem.

Given the two arrays of length n and m, each of the result arrays in your
answer are going to be length n+m. Think of each element in those arrays as a
binary decision between choosing the next element of each array - there will
be C(n+m,n) possible outcomes - and this is just a bit string where a 0 means
take the next element from the first array and a 1 from the second array. Once
you see this, it is just a matter of generating all length n+m bit strings
with exactly n 0-bits.

This is the next permutation problem which can be done in constant space and
linear time and very efficiently too. C++ even has an STL function for it:
[http://www.cplusplus.com/reference/algorithm/next_permutatio...](http://www.cplusplus.com/reference/algorithm/next_permutation/)

Your starting array is '0011' in his example, then keep generating the next
permutation in a loop until exhausted so '0101', '0110', etc...

edit: here's a cute bit hack for it too:
[https://graphics.stanford.edu/~seander/bithacks.html#NextBit...](https://graphics.stanford.edu/~seander/bithacks.html#NextBitPermutation)

~~~
bobbiechen
Great point that since relative order is fixed, it's just a binary decision.

A similar problem (with the same solution described) is "balls and bins" [1]:
you have k identical balls and n bins - how many ways are there to place the
balls in the bins? It blew my mind in intro to discrete math when we
reconsidered the problem with instead of n bins, (n-1) bin _dividers_. Then
simply choose where to place the (n-1) dividers out of (k+n-1) places for all
of your objects, and you're done!

[1] [https://artofproblemsolving.com/wiki/index.php/Ball-and-
urn](https://artofproblemsolving.com/wiki/index.php/Ball-and-urn)

------
neonate
[https://web.archive.org/web/20190818001643/http://mohit.athw...](https://web.archive.org/web/20190818001643/http://mohit.athwani.net/backtracking/weaving-
two-arrays/)

------
cfors
Your site is down, FYI.

> Error establishing a database connection

~~~
yardshop
It's a very beautiful error message anyway.

