Generate a matrix containing all combinations of elements from n vectors (Cartesian product)

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

Algorithm to select a single, random combination of values?

Robert Floyd invented a sampling algorithm for just such situations. It’s generally superior to shuffling then grabbing the first x elements since it doesn’t require O(y) storage. As originally written it assumes values from 1..N, but it’s trivial to produce 0..N and/or use non-contiguous values by simply treating the values it produces as subscripts into …

Read more

Find all combinations of a list of numbers with a given sum

You could use itertools to iterate through every combination of every possible size, and filter out everything that doesn’t sum to 10: import itertools numbers = [1, 2, 3, 7, 7, 9, 10] target = 10 result = [seq for i in range(len(numbers), 0, -1) for seq in itertools.combinations(numbers, i) if sum(seq) == target] print(result) …

Read more