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

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

JavaScript – Generating combinations from n arrays with m elements [duplicate]

Here is a quite simple and short one using a recursive helper function: function cartesian(…args) { var r = [], max = args.length-1; function helper(arr, i) { for (var j=0, l=args[i].length; j<l; j++) { var a = arr.slice(0); // clone arr a.push(args[i][j]); if (i==max) r.push(a); else helper(a, i+1); } } helper([], 0); return r; } … 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