Skip to content
Advertisement

All combinations of r elements from given array php

Given an array such as the following

JavaScript

I’m looking for a method to generate all possible combinations, with a minimum number of elements required in each combination r. (eg if r = 5 then it will return all possible combinations containing at least 5 elements)

Advertisement

Answer

A combination can be expressed as

nCr = n! / (r! – (n – r)!)

First, we determine $n as the number of elements in the array. And $r is the minimum number of elements in each combination.

JavaScript

Next, we determine $max as the maximum number that can be represented by $n binary digits. That is, if $n = 3, then $max = (111)2 = 7. To do this, we first create a empty string $maxBinary and add $n number of 1s to it. We then convert it to decimal, and store it in $max.

JavaScript

Then, we list out every binary number from 0 to $max and store those that have more than $r number of 1s in them.

JavaScript

Then, we use the same trick as above to select elements for our combination. I believe the comments explain enough.

JavaScript

And that is it. You are done!

Now if you have something like

JavaScript

then it would give you 29.

Additional notes:

I read up on this only after seeing your question, and as a newcomer, I found these useful:

Also, here are some quick links to the docs, that should help people who see this in the future:

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