Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I think this should work:</p> <pre><code>var a = [1, 3, 5, 9]; var l = a.length; var r = []; for (var i = 0; i &lt; l; ++i) { for (var j = i + 1; j &lt; l; ++j) { for (var k = j + 1; k &lt; l; ++k) { r.push(a[i] * a[j] * a[k]); } } } </code></pre> <p><strong>Edit</strong></p> <p>Just for my own edification, I figured out a generic solution that uses loops instead of recursion. It's obvious downside is that it's longer thus slower to load or to read. On the other hand (at least on Firefox on my machine) it runs about twice as fast as the recursive version. However, I'd only recommend it if you're finding combinations for large sets, or finding combinations many times on the same page. Anyway, in case anybody's interested, here's what I came up with.</p> <pre><code>function combos(superset, size) { var result = []; if (superset.length &lt; size) {return result;} var done = false; var current_combo, distance_back, new_last_index; var indexes = []; var indexes_last = size - 1; var superset_last = superset.length - 1; // initialize indexes to start with leftmost combo for (var i = 0; i &lt; size; ++i) { indexes[i] = i; } while (!done) { current_combo = []; for (i = 0; i &lt; size; ++i) { current_combo.push(superset[indexes[i]]); } result.push(current_combo); if (indexes[indexes_last] == superset_last) { done = true; for (i = indexes_last - 1; i &gt; -1 ; --i) { distance_back = indexes_last - i; new_last_index = indexes[indexes_last - distance_back] + distance_back + 1; if (new_last_index &lt;= superset_last) { indexes[indexes_last] = new_last_index; done = false; break; } } if (!done) { ++indexes[indexes_last - distance_back]; --distance_back; for (; distance_back; --distance_back) { indexes[indexes_last - distance_back] = indexes[indexes_last - distance_back - 1] + 1; } } } else {++indexes[indexes_last]} } return result; } function products(sets) { var result = []; var len = sets.length; var product; for (var i = 0; i &lt; len; ++i) { product = 1; inner_len = sets[i].length; for (var j = 0; j &lt; inner_len; ++j) { product *= sets[i][j]; } result.push(product); } return result; } console.log(products(combos([1, 3, 5, 7, 9, 11], 3))); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload