public static List <string> BuildCode(List <string> dictionary) { var encodedDictionary = new List <string>(); int codeLength = (int)Math.Ceiling(Math.Log(dictionary.Count, 2)); for (int j = 0; j < dictionary.Count; j++) { var code = new BitArray(BitConverter.GetBytes(j)); String stringCode = StringManipulator.BitToString(code, codeLength); if (!encodedDictionary.Contains(stringCode)) { encodedDictionary.Add(stringCode); } } MessageBox.Show("Средняя длинна кодового слова: " + codeLength.ToString()); return(encodedDictionary); }
public List <string> Encode(List <string> dictionary) { var result = new List <string>(); for (int i = 0; i < dictionary.Count; i++) { List <bool> encodedSymbol = Root.Traverse(dictionary[i], new List <bool>()); result.Add(StringManipulator.BitToString(new BitArray(encodedSymbol.ToArray()))); b += result[i].ToString().Length *d[dictionary[i]]; c += d[dictionary[i]]; } MessageBox.Show("Средняя длинна кодового слова: " + b.ToString()); return(result); }
private void button1_Click(object sender, EventArgs e) { var dictionary = new List <string>(); List <string> encodedDictionary; var encodedText = new List <string>(); var encodedBuilder = new StringBuilder(); string decodedText = string.Empty; var sourceText = FileManipulator.ReadFile(openFileDialog1); int blockLength = (int)numericUpDown1.Value; int step = radioButton1.Checked ? blockLength : 1; var splittedText = StringManipulator.SplitText(sourceText, step, blockLength, dictionary); if (radioButton3.Checked) { encodedDictionary = SimpleCode.BuildCode(dictionary); } else { encodedDictionary = HaffmanCode.BuildCode(splittedText, dictionary); } for (int m = 0; m < splittedText.Count; m++) { int index = dictionary.IndexOf(splittedText[m]); string stringCode = encodedDictionary[index]; encodedText.Add(stringCode); encodedBuilder.Append(stringCode); } FileManipulator.WriteFile(encodedBuilder.ToString(), "encoded.txt"); int encodedLength = encodedBuilder.ToString().Length; int sourceLength = sourceText.ToString().Length; float compression = (float)sourceLength / encodedLength; MessageBox.Show("Длина исходного текста=" + sourceLength.ToString() + "\nДлина закодированного текста=" + encodedLength.ToString() + "\nКоэфициент сжатия=" + compression.ToString()); if (radioButton1.Checked) { for (int k = 0; k < encodedText.Count; k++) { int index = encodedDictionary.IndexOf(encodedText[k]); decodedText += dictionary[index];// если меньше 5 глючит } FileManipulator.WriteFile(decodedText, "decodedBlock.txt"); } if (radioButton2.Checked) { decodedText += dictionary[encodedDictionary.IndexOf(encodedText[0])]; for (int i = 1; i < encodedText.Count; i++) { int index = encodedDictionary.IndexOf(encodedText[i]); string t = dictionary[index]; t = t.Substring(blockLength - 1, 1); decodedText += t; } FileManipulator.WriteFile(decodedText, "decodedLGramm.txt"); } }