How to calculate the max. number of combinations possible?

Ali picture Ali · Aug 6, 2010 · Viewed 28.7k times · Source

Possible Duplicates:
Display possible combinations of string
algorithm that will take numbers or words and find all possible combinations

If I have 3 strings, such as:

"abc def xyz"

And I want to find the max number of combinations I can generate by rearranging these strings, e.g:

  • abc xyz def
  • def xyz abc
  • xyz abc def

etc. What's the formula/algorithm for calculating this?

Answer

This is not a combination but permutation. The algorithm is n! where n is the number of elements.

Why ?

Because you have 3 values to place on three places, so for the first place You have three option, for second only two (becuase You already palace first string) and at the end You have only one option.

3 * 2 * 1 = 3! = 6

But if You can repeate those chooses than you have permutation with repetition

So for first place You can chose from 3 string and for the second also and so one

3 * 3 * 3 = 3^3 = 27

n^k - where n is the number of strings and k - the number of "locations"

And the code algorithm look like this:

function fact($n)
{
  if ($n == 0)
  {
    return 1;
  }
  else
  {
    return $n * fact($n - 1);
  }
}

This is a recursive example