Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters is done just like they are arranged on a telephone keypad.
Looking for ways of making the code more consise and easily readable. Want to learn the C# tricks to make solving or implementing this solution easier.
using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
LetterCombinations("34");
}
public static void LetterCombinations(String number)
{
string[][] StringMapping = new string[number.Length][];
int LengthIndex = 0;
foreach (char c in number)
{
switch (c)
{
case '2':
StringMapping[LengthIndex] = new string[] {"a", "b", "c"};
break;
case '3':
StringMapping[LengthIndex] = new string[] {"d", "e", "f"};
break;
case '4':
StringMapping[LengthIndex] = new string[] {"g", "h", "i"};
break;
case '5':
StringMapping[LengthIndex] = new string[] {"j", "k", "l"};
break;
case '6':
StringMapping[LengthIndex] = new string[] {"m", "n", "o"};
break;
case '7':
StringMapping[LengthIndex] = new string[] {"p", "q", "r", "s"};
break;
case '8':
StringMapping[LengthIndex] = new string[] {"t", "u", "v"};
break;
case '9':
StringMapping[LengthIndex] = new string[] {"w", "x", "y", "z"};
break;
}
LengthIndex++;
}
int[] SizeArray = new int[StringMapping.Length]; //Keeps track of the size of each inner String array
int[] counterArray = new int[StringMapping.Length]; //Keeps track of the index of each inner String array, which will be used to make the next combination
//Discover the size of each inner array and populate sizeArray.
//Also calculate the total number of combinations possible using the inner String array sizes.
int totalCombinationCount = 1;
for (int i = 0; i < StringMapping.Length; i++)
{
SizeArray[i] = StringMapping[i].Length;
totalCombinationCount *= StringMapping[i].Length;
}
//Store the combinations in a List of String objects
List<String> combinationList = new List<String>(totalCombinationCount);
String sb = "";
for (int countdown = totalCombinationCount; countdown > 0; countdown--)
{
sb = "";
for (int i = 0; i < StringMapping.Length; i++)
{
sb += StringMapping[i][counterArray[i]];
}
combinationList.Add(sb.ToString());
//Now we need to increment the counterArray so that the next
//combination is taken on the next iteration of this loop.
for (int incIndex = StringMapping.Length - 1; incIndex >= 0; incIndex--)
{
if (counterArray[incIndex] + 1 < SizeArray[incIndex])
{
++counterArray[incIndex];
break;
}
counterArray[incIndex] = 0;
}
}
//Output the strings in the list
foreach (String s in combinationList)
{
Console.WriteLine(s);
}
}
}
}