-
Feb 20th, 2012, 03:10 PM
#1
Thread Starter
Frenzied Member
Mono-alphabetic substitution
Hi,
So I'm working on this mono-alphabetic substitution system, which - for the people unfamiliar with it - basically means that you substitute every letter with another one in the alphabet using a key.
It's the most basic form of encryption.
The problem I'm having (I mean it works, but seems rather inefficient) is that you can't just loop through the alphabet and replace each character with it's substitute, because you would come to a point where you replace an already replaced character.
For example:
- Take the string 'abcde'
- Replace occurences of 'a' with 'b' - resulting into 'bbcde'
- And now replace occurences of 'b' with 'e' - resulting into 'eecde'
Where the desired result would be 'becde'.
To solve this I've used the following:
Code:
for (int i = 0; i < keyLength; i++)
{
for (int j = 0; j < textLength; j++)
{
if (text[j] == key[i])
decoded[j] = this._referenceKey[i];
}
}
It works, but if the text is long enough this solution is rather slow.
Is there a nicer solution for something like this?
Thanks!
Delete it. They just clutter threads anyway.
-
Feb 20th, 2012, 08:57 PM
#2
Re: Mono-alphabetic substitution
Well, assuming you've got a replacement function for a given character (my example code was hastily written and frankly sucks at that aspect), then you could try the following:
- Take the string 'abcde'
- Read the first character 'a' and output 'b'
- Read the second character 'b' and output 'e'
- Read the third character 'c' and output 'c'
- Read the fourth character 'd' and output 'd'
- Read the fifth character 'e' and output 'e'
it could look something like this (caveat replacement function):
csharp Code:
class Program { static void Main (string[] args) { string plaintext = "Hello World"; IEnumerable<char> cipherTextStream = plaintext.ToCharArray().Select(GetCaesarShift(3)); string cipherText = new string(cipherTextStream.ToArray()); Console.WriteLine(cipherText); Console.ReadLine(); } static Func<char, char> GetCaesarShift(int shiftBy) { return c => Char.IsLetter(c) ? (char)(c + shiftBy) : c; } }
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|