CrAzYPiLoT CrAzYPiLoT - 1 month ago 17
C# Question

Iterative decoding

So, I have a cipher that I would need to break. I have the key, but the problem is that every number in a cipher corresponds to three or two letters. For example, if we had the cipher '12', and we know that '1' corresponds to either 'A', 'J' or 'S', and '2' corresponds to 'B', 'K' or 'T', we would need to output all possible combinations, so: 'AB', 'AK', 'AT', 'JB', 'JK', 'JT', 'SB', 'SK', 'ST'. How would I go around doing this in C#?

Thanks in advance.

Answer

Using LINQ you can use following code:

var input = "12";

var mappings = new Dictionary<string, string[]>();
mappings.Add("1", new string[] { "A", "J", "S" });
mappings.Add("2", new string[] { "B", "K", "T" });

var result = input.Select(c => mappings[c.ToString()]).CartesianProduct();

foreach (var item in result)
{
    Console.WriteLine(string.Join("", item.ToArray()));
}

It uses the CartesianProduct extension method from Eric Lipperts blog

Cant get much easier