15,923,142 members
See more:
Hi there,

I have a string array of length 3. The array is just {"A", "B", "C"}. I have been scratching my head a while in how to possible print out all the combinations for this.

Just to not the size of array can vary so embedding 3 for loops is not a successful solution even though it works great. GRRR.

I want to print out all the 3 letter combos i.e ABC, CAB etc with no letter repition in the output string. There are 6 in total for this case. For others I get the factorial for the array length.

Any suggestions are welcome and thanks in advance for any hel that may be received
Posted

## Solution 4

"I want to print out all the 3 letter combos i.e ABC, CAB etc with no letter repition in the output string. There are 6 in total for this case. For others I get the factorial for the array length." aka Permutation.

You can review LINQ+Recursion implementation(a la "smart" multiloop in recursion), like this:

C#
```public static IEnumerable<string> GetPermutation(string s)
{
if (s.Length > 1) {
return from c in s
from p in GetPermutation(s.Remove(s.IndexOf(c), 1))
select c+p;
} else {
return new string[] { s };
}
}```

Code from http://stackoverflow.com/questions/774457/combination-generator-in-linq[

v3
ProEnggSoft 19-Mar-12 6:51am
Good solution. 5!
IndexOf(ch) should be IndexOf(c)
I have edited it.
BobJanova 19-Mar-12 7:00am
Clever. Gets my 5, even if it is a repost from SO.

## Solution 1

Go recursive: recursion would do the job.

## Solution 2

If you aren't particularly worried about speed and space issues, the simplest way to do it would be to use recursion.

Basically something on the order of this pseudo-code:

C++
```print_all_combinations_of( input_array ) {

size = input_array.count

if ( size == 1 ) {

print input_array[0] + "\n"

} else {

for ( i = 0 ; i < size; i++ ) {

print input_array[i]

array_without_element_i = new array( input_array )

array_without_element_i.remove_element_at(i)

print_all_combinations_of ( array_without_element_i )

}

}

}```