Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Permutations of capitalization

I want to build a list containing every possible permutation of capitalization of a word. so it would be

List<string> permutate(string word)
{
    List<string> ret = new List<string>();
    MAGIC HAPPENS HERE
    return ret;
}

So say I put in "happy" I should get an array back of

{happy, Happy, hAppy, HAppy, haPpy, HaPpy ... haPPY, HaPPY, hAPPY, HAPPY}

I know of plenty of functions that will capitalize the first letter but how do I do any arbitrary letter in the word?

like image 711
Scott Chamberlain Avatar asked May 25 '09 04:05

Scott Chamberlain


1 Answers

You can modify individual characters if you convert your string to an array of char. Something like this should do the trick...

public static List<string> Permute( string s )
{
  List<string> listPermutations = new List<string>();

  char[] array = s.ToLower().ToCharArray();
  int iterations = (1 << array.Length) - 1;

  for( int i = 0; i <= iterations; i++ )
  {
    for( int j = 0; j < array.Length; j++ )
    array[j] = (i & (1<<j)) != 0 
                  ? char.ToUpper( array[j] ) 
                  : char.ToLower( array[j] );
    listPermutations.Add( new string( array ) );
  }
  return listPermutations;
}
like image 116
LBushkin Avatar answered Sep 27 '22 18:09

LBushkin