M
M
Maxim Isaev2018-11-26 20:21:45
.NET
Maxim Isaev, 2018-11-26 20:21:45

Where is the error in the enumeration?

the task is to recurse through all possible combinations for an array of characters in upper and lower case. The input is an array with lowercase characters. As an example, he gave an array of characters char[] ch = new char[3] { 'c', 'a', 't' };
When running through tests on the course site, the combination ('C','a','T') was not found.

public static List<string> AlternateCharCases(string lowercaseWord)
        {
            var result = new List<string>();
            AlternateCharCases(lowercaseWord.ToCharArray(), 0, result);
            var distinctRes = result.Distinct().ToList();
            return distinctRes;
        }
 static void AlternateCharCases(char[] word, int startIndex, List<string> result)
        {
            var tmpVarriable = word.ToArray();
            if (word.Length == startIndex)
            {
                result.Sort();
                return;
            }
            for (int i = startIndex; i < word.Length; i++)
            {
                result.Add(new string(word));
                word[i] = char.ToUpper(word[i]);
                result.Add(new string(word));
            }
            AlternateCharCases(tmpVarriable, startIndex + 1, result);
        }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Vlasov, 2018-11-27
@MaximIs

I do not understand why this cycle is inside the method. It can be done a little easier. The idea is to change the case of the letter word[startIndex] to lowercase on each call to the AlternateCharCases method and call the same method with the startIndex offset , then change the case to uppercase and call the same method again. Probably not very clear, here is the working code:

static void AlternateCharCases(char[] word, int startIndex, List<string> result)
{
     if (word.Length == startIndex)
     {
          result.Add(new string(word));
          return;
     }
     word[startIndex] = char.ToLower(word[startIndex]);
     AlternateCharCases(word, startIndex + 1, result);
     word[startIndex] = char.ToUpper(word[startIndex]);
     AlternateCharCases(word, startIndex + 1, result);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question