Results 1 to 2 of 2

Thread: Mono-alphabetic substitution

  1. #1

    Thread Starter
    Frenzied Member TheBigB's Avatar
    Join Date
    Mar 2006
    Location
    *Stack Trace*
    Posts
    1,511

    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.

  2. #2
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    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:
    1. class Program {
    2.     static void Main (string[] args)
    3.     {
    4.         string plaintext = "Hello World";
    5.  
    6.         IEnumerable<char> cipherTextStream = plaintext.ToCharArray().Select(GetCaesarShift(3));
    7.  
    8.         string cipherText = new string(cipherTextStream.ToArray());
    9.  
    10.         Console.WriteLine(cipherText);
    11.         Console.ReadLine();
    12.     }
    13.  
    14.     static Func<char, char> GetCaesarShift(int shiftBy)
    15.     {
    16.         return c => Char.IsLetter(c)
    17.             ? (char)(c + shiftBy)
    18.             : c;
    19.     }
    20. }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width