public static Dictionary <char, char> GetOptimalCharacterMappingNonCaesar(Dictionary <char, double> textCharProportion, Dictionary <char, double> targetCharProportion, out double mappingDifference) { /*Mappings are { inputTextChar : actualChar }*/ double minDifference = double.MaxValue; Dictionary <char, char> optimalMapping = null; foreach (List <char> charList in ProgramMath.GetPermutations(new List <char>(Program.validCharacters))) { /*Create Character Mapping*/ Dictionary <char, char> mapping = new Dictionary <char, char>(); for (int i = 0; i < Program.validCharacters.Length; i++) { mapping[charList[i]] = Program.validCharacters[i]; } /*Test character mapping*/ Dictionary <char, double> mappedCharProportions = new Dictionary <char, double>(); foreach (char key in textCharProportion.Keys) { mappedCharProportions[mapping[key]] = textCharProportion[key]; } double difference = ProgramMath.GetKeyFrequencyDifference(mappedCharProportions, targetCharProportion); /*Compare mapping to best*/ if (difference < minDifference) { minDifference = difference; optimalMapping = new Dictionary <char, char>(mapping); } } mappingDifference = minDifference; return(optimalMapping); }
public static Dictionary <char, char> GetOptimalCharacterMapping(Dictionary <char, double> textCharProportion, Dictionary <char, double> targetCharProportion, out double mappingDifference, out int mappingShiftAmount) { /*Mappings are { inputTextChar : actualChar }*/ double minDifference = double.MaxValue; Dictionary <char, char> optimalMapping = null; int optimalShiftAmount = 0; for (int i = 0; i < 26; i++) { /*Create Character Mapping*/ Dictionary <char, char> mapping = ProgramMath.GetCharacterMappingByCaesarCipherOffset((26 - i) % 26); /*Test character mapping*/ Dictionary <char, double> mappedCharProportions = new Dictionary <char, double>(); foreach (char key in textCharProportion.Keys) { mappedCharProportions[mapping[key]] = textCharProportion[key]; } double difference = ProgramMath.GetKeyFrequencyDifference(mappedCharProportions, targetCharProportion); /*Compare mapping to best*/ if (difference < minDifference) { minDifference = difference; optimalMapping = new Dictionary <char, char>(mapping); optimalShiftAmount = i; } } mappingDifference = minDifference; mappingShiftAmount = optimalShiftAmount; return(optimalMapping); }