Without using any fancy library function (so let's use JavaScript), what is a way to get all combinations of picking k
items from an n
-item array of distinct values? (0 <= k <= n
)
That is, if the array is [1,2,3]
, then the result should be:
[[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
Note the size of the given array is not fixed. So it can be [1,2,3,4]
or [1,"a","b","c",5,100]
I could think of a way which is to use a binary number with n
digits, for example, with n = 3
, starting with
000
and adding 1 to it, and repeat until 111
, and 000
means no element get in, and 001
means the last element gets in, and 011
means the last 2 elements get in, and we would get all the possibilities, but it is a pretty strange way to solve it and it seems there should be a more elegant solution.