public Analysis(int timeout = 10) { sb = new SubstitutionCipher(); NgramsDictionary = parseNgramsFile(); worstScore = Math.Log10(0.01 / totalNgrams); if (timeout > 30) { this.timeout = 10; } else { this.timeout = timeout; } }
public string breakSubstitutionCipher(string cipherText) { //current int count = 0; string maxKey = SubstitutionCipher.getAlphabet(); double maxScore = -99e9; string parentKey = maxKey; double parentScore = maxScore; DateTime start = DateTime.Now; while (DateTime.Now.Subtract(start).Seconds <= timeout) { count++; parentKey = sb.generateNewKey(); parentScore = getTextNgramFitness(sb.decode(cipherText, parentKey)); for (int i = 0; i < 1000; i++)//i => iterations since last improvement. If > 1000, we are at local maximum { string childKey = sb.swapTwoChars(parentKey); double childScore = getTextNgramFitness(sb.decode(cipherText, childKey)); if (childScore > parentScore) { parentScore = childScore; parentKey = childKey; i = 0;//made an improvement, reset counter } } if (parentScore > maxScore) { maxScore = parentScore; maxKey = parentKey; } } return(maxKey); }