Click here to Skip to main content
15,885,919 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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

"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[
 
Share this answer
 
v3
Comments
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.
Go recursive: recursion would do the job.
 
Share this answer
 
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 )

       }

   }

}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900