Skip to content

Instantly share code, notes, and snippets.

@martani
Created April 27, 2011 19:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martani/944963 to your computer and use it in GitHub Desktop.
Save martani/944963 to your computer and use it in GitHub Desktop.
Frequency Analysis on a text (Caesar cipher + key search)
static Dictionary<char, double> AnalyseFrequency(string text)
{
if (text == null)
return null;
Dictionary<char, double> frequencies = new Dictionary<char, double>();
int textLength = text.Length;
for (int i = 0; i < textLength; i++)
{
char c = text[i];
char key = '#';
//ignore chars that are not letters
if ((c >= 'a' && c <= 'z'))
key = c;
if (c >= 'A' && c <= 'Z')
key = (char)(c + 'a' - 'A');
if (frequencies.Keys.Contains(key))
frequencies[key] = frequencies[key] + 1;
else
frequencies[key] = 1;
}
//cannot enumerate throught the dictionnay keys directly.
List<char> keys = frequencies.Keys.ToList();
foreach (char c in keys)
{
frequencies[c] /= textLength;
}
return frequencies;
}
frequencies = AnalyseFrequency(caesarCryptogram);
double maxFreq = frequencies.Values.Max();
char maxChar = frequencies.Keys.Where(c => frequencies[c] == maxFreq).FirstOrDefault();
//'E' is the maxChar
Console.WriteLine(string.Format("E is probably: {0} - {1}", maxChar, maxFreq));
Console.WriteLine(string.Format("Key would be: {0}", (char) (maxChar - 'e' + 'A')));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment