Skip to content
Advertisement

Generate unique combinations in JavaScript from n objects with r samples

What is the best way to generate all unique combinations in JavaScript from N objects with R samples. For example:

JavaScript

Expected result

JavaScript

I am able to achieve above using recursive solution. But it is slow for large datasets (e.g. N=25, R=10). Is there any faster way to achieve this?

Advertisement

Answer

Ok, here a straight implementation of a sequential generator as described in Wikipedia:

…track k index numbers of the elements selected, starting with {0 .. k−1} (zero-based) or {1 .. k} (one-based) as the first allowed k-combination and then repeatedly moving to the next allowed k-combination by incrementing the last index number if it is lower than n-1 (zero-based) or n (one-based) or the last index number x that is less than the index number following it minus one if such an index exists and resetting the index numbers after x to {x+1, x+2, …}. https://en.wikipedia.org/wiki/Combination#Enumerating_k-combinations

JavaScript

Takes < 1 sec on my machine.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement