How can I create every combination possible for the contents of two arrays?

Or if you’d like to create combinations with an arbitrary number of arrays of arbitrary sizes…(I’m sure you can do this recursively, but since this isn’t a job interview, I’m instead using an iterative “odometer” for this…it increments a “number” with each digit a “base-n” digit based on the length of each array)…for example… combineArrays([ … Read more

How to generate in PHP all combinations of items in multiple arrays

Here is recursive solution: function combinations($arrays, $i = 0) { if (!isset($arrays[$i])) { return array(); } if ($i == count($arrays) – 1) { return $arrays[$i]; } // get combinations from subsequent arrays $tmp = combinations($arrays, $i + 1); $result = array(); // concat each array from tmp with each element from $arrays[$i] foreach ($arrays[$i] as … Read more

Generate a matrix containing all combinations of elements taken from n vectors

The ndgrid function almost gives the answer, but has one caveat: n output variables must be explicitly defined to call it. Since n is arbitrary, the best way is to use a comma-separated list (generated from a cell array with ncells) to serve as output. The resulting n matrices are then concatenated into the desired … Read more

Making all possible combinations of a list [duplicate]

Simply use itertools.combinations. For example: import itertools lst = [1, 2, 3] combs = [] for i in xrange(1, len(lst)+1): combs.append(i) els = [list(x) for x in itertools.combinations(lst, i)] combs.append(els) Now combs holds this value: [1, [[1], [2], [3]], 2, [[1, 2], [1, 3], [2, 3]], 3, [[1, 2, 3]]] Yes, it’s slightly different from … Read more