0

What data structure better stores the following substitution-cipher letter mappings?

abcdefghijklmnopqrstuvwxyz
qpalzxmskwoeidjcnvbfhguryt

I am currently using two dictionaries, but there must be something simpler:

char[] alphabet = {'a', 'b', 'c', 'd', 'e',
                   'f', 'g', 'h', 'i', 'j',
                   'k', 'l', 'm', 'n', 'o',
                   'p', 'q', 'r', 's', 't',
                   'u', 'v', 'w', 'x', 'y', 'z'};
char[] mappings = {'q', 'p', 'a', 'l', 'z',
                   'x', 'm', 's', 'k', 'w',
                   'o', 'e', 'i', 'd', 'j',
                   'c', 'n', 'v', 'b', 'f',
                   'h', 'g', 'u', 'r', 'y', 't'};

Dictionary<char, char> encrypt = new Dictionary<char, char>();
Dictionary<char, char> decrypt = new Dictionary<char, char>();

for (int i = 0; i < 26; i++)
{
    encrypt.Add(alphabet[i], mappings[i]);
    decrypt.Add(mappings[i], alphabet[i]);
}
wjmolina
  • 2,625
  • 2
  • 26
  • 35
  • Your approach of using two dictionaries is fine but I would wrap that into one class as [shown here](http://stackoverflow.com/a/255630/187697). – keyboardP Jul 25 '13 at 18:13

2 Answers2

1

Your approach is already the best. However, try wrapping your dictionaries in a class, as Jon Skeet does here: Getting key of value of a generic Dictionary?

Community
  • 1
  • 1
0

Here's how you can simplify things:

just use a char[] for encrypt, and another for decrypt. You can index it by the ascii value of the letter, so you use a larger array (256 instead of 26) but the code's much simpler.

Consider something like this:

string mapping="bcdefghij...za"; // simple example to code 'a' as 'b'.

char[] encode = new char[256];
char[] decode = new char[256];

for (char a='a'; a<='z'; a++) {
  encode[a]=mapping[a-'a'];
  decode[ mapping[a-'a'] ] = a;
}

Then you can use LINQ for the encode function, something like this:

string encodeString(string plaintext) {
  return new string( plaintext.Select(c=>encode[c]).ToArray() );
}

You're probably going to have to add a few type conversions in there (I didn't try compiling the code), but the idea's all here.

redtuna
  • 4,586
  • 21
  • 35