// Проверка правильности строки для кода Хаффмана public static ReturnResult CheckString04(string reply, string generated) { try { bool yes = true; string input = generated; if (input.CompareTo("") == 0) { return new ReturnResult(false, "Вы не ввели текст!"); } HuffmanTree huffmanTree = new HuffmanTree(); // Строим дерево Хаффмана по весам слов huffmanTree.Build(input); // Кодируем BitArray encoded = (BitArray)huffmanTree.Encode(input); if (huffmanTree.str != reply) yes = false; if (yes) return new ReturnResult(true, "Абсолютно верное решение! "); return new ReturnResult(false, "Это не оптимальный код Хаффмана. Вот он: " + huffmanTree.str); } catch (Exception e) { return new ReturnResult(false, "Ошибка ввода! " + e.Message); } }
static void Main(string[] args) { BitArray encoded; char input = ' '; string pathtofile; Console.WriteLine("Input path to file"); pathtofile = Console.ReadLine(); HuffmanTree huffmanTree = new HuffmanTree(); using (BinaryReader sr = new BinaryReader(new FileStream(pathtofile, FileMode.Open), Encoding.UTF8)) huffmanTree.Build(input, sr); using (BinaryReader sr = new BinaryReader(new FileStream(pathtofile, FileMode.Open), Encoding.UTF8)) encoded = huffmanTree.Encode(input, sr); Console.Write("Encoded "); string bytestr = ""; int i = 0; while (i < encoded.Length) { if (bytestr.Length < 8) { bytestr += encoded[i] ? 1 : 0.ToString(); i++; } else { HuffmanTree.bytes.Add(Convert.ToByte(bytestr, 2)); bytestr = ""; } } if (bytestr.Length <= 8) { while (bytestr.Length < 8) { bytestr += "0"; Node.Delta++; } HuffmanTree.bytes.Add(Convert.ToByte(bytestr, 2)); } using (StreamWriter sw = new StreamWriter("archive.txt", false)) { sw.Write(Node.EncTree(huffmanTree.Root)); } using (FileStream fs = new FileStream("archive.txt", FileMode.Append)) { fs.Write(HuffmanTree.bytes.ToArray()); fs.WriteByte(Node.Delta); } Console.WriteLine(); huffmanTree.Root = new Node(); huffmanTree.Decode(); Console.WriteLine("Decoded"); Console.WriteLine("All done"); Console.ReadLine(); }
public static void Encode(string arquivo) { LZWEncoder encoder = new LZWEncoder(); string conteudo = Arquivo.Abrir(arquivo); Console.WriteLine("Iniciada a compressão"); DateTime dataInicial = DateTime.Now; //Codificação LZW string lzwEncoded = encoder.Encode(conteudo); HuffmanTree huffman = new HuffmanTree(); //Criação da árvore huffman huffman.Build(lzwEncoded); //Codificação huffman var huffmanEncoded = huffman.Encode(lzwEncoded); DateTime dataFinal = DateTime.Now; string tempoDecorrido = (dataFinal - dataInicial).TotalSeconds.ToString("N2"); //Contabiliza apenas os tempos para compressão. Igora tempo de IO Console.WriteLine($"Arquivo comprimido em {tempoDecorrido} segundos"); byte[] ret = new byte[(huffmanEncoded.Length - 1) / 8 + 1]; huffmanEncoded.CopyTo(ret, 0); //Gravando arquivo comprimido Arquivo.Gravar(ret, $"{arquivo.Split('.')[0]}.scps"); }
public void TestEncodeDecodeWithCompression() { var input = "He paused for a moment, many recollections overpowering him. Then he went on telling her the history of his life, unfolding to her the story of his hopes and ambitions, describing to her the very home where he was born, and the dark-eyed sister whom he had loved, and with whom he had played over the daisied fields, and through the carpeted woods, and all among the richly tinted bracken. One day he was told she was dead, and that he must never speak her name; but he spoke it all the day and all the night, Beryl, nothing but Beryl, and he looked for her in the fields and in the woods and among the bracken. It seemed as if he had unlocked the casket of his heart, closed for so many years, and as if all the memories of the past and all the secrets of his life were rushing out, glad to be free once more, and grateful for the open air of sympathy."; var dict = CharacterFrequencyDictionary.CreateDictionary(input); var encodeTree = new HuffmanTree<char>(dict); var encode = encodeTree.Encode(input); var encodeAsByte = CompressUtil.ConvertToByteArray(encode); var secondDict = CharacterFrequencyDictionary.CreateDictionary( dict.GetKeysAsByteArray(), dict.GetValuesAsByteArray()); var encodeAsByteArray = new List<byte>(); foreach (var b in encodeAsByte) encodeAsByteArray.AddRange(CompressUtil.ConvertToBitArray(b)); if (encode.Length < encodeAsByteArray.ToArray().Length) encodeAsByteArray.RemoveRange(encode.Length, encodeAsByteArray.ToArray().Length - encode.Length); CollectionAssert.AreEqual(dict, secondDict); CollectionAssert.AreEqual(encode, encodeAsByteArray.ToArray()); var decodeTree = new HuffmanTree<char>(secondDict); var decode = decodeTree.Decode(encodeAsByteArray); Assert.AreEqual(input, decode); }
public static Dictionary <char, string> Solve(int[] frequency) { HuffmanTree tree = new HuffmanTree(); tree.BuildHuffmanTree(frequency); var dict = tree.Encode(); return(dict); }
private void button9_Click(object sender, EventArgs e) { var watch = new System.Diagnostics.Stopwatch(); var watch2 = new System.Diagnostics.Stopwatch(); for (int s = min; s < max; s += step) { generatingbench(s); BitArray temp = null; for (int i = 0; i < nor; i++) { watch.Restart(); compress(inputbench.ToString()); huffmanTree = new HuffmanTree(); huffmanTree.Build(compressed.ToString()); BitArray encoded2 = huffmanTree.Encode(compressed.ToString()); benchmarktime1 += watch.Elapsed.TotalMilliseconds; if (i == 0) { temp = huffmanTree.Encode(compressed.ToString()); } watch.Stop(); } //================================================================================================== for (int i = 0; i < nor; i++) { watch2.Restart(); decompress(); string decoded = huffmanTree.Decode(temp); benchmarktime2 += watch2.Elapsed.TotalMilliseconds; watch2.Stop(); } if (s == min) { this.richTextBox13.Text = "Data Size \t" + "Compress time \t" + "Decompress Time \t" + "\n" + "=====================================================" + "\n"; } this.richTextBox13.Text += s + "\t\t" + Math.Round((benchmarktime1 / nor), 3).ToString() + "\t\t" + Math.Round((benchmarktime2 / nor), 3).ToString() + "\n"; benchmarktime1 = 0; benchmarktime2 = 0; } }
public void TestHuffmanCodingProblem() { HuffmanTree hfmTree = new HuffmanTree(); string input = "sankara loves devi"; hfmTree.Build(input); BitArray encoded = hfmTree.Encode(input); string decoded = hfmTree.Decode(encoded); Assert.IsTrue(input == decoded); }
public void HuffmanTree_Encode_Decode(int count) { var sourceStr = CreateString(count); var sourceBytes = Encoding.UTF8.GetBytes(sourceStr); var cipherBytes = HuffmanTree.Encode(sourceBytes); var plainBytes = HuffmanTree.Decode(cipherBytes); var plainStr = Encoding.UTF8.GetString(plainBytes); Assert.Equal(sourceStr.Length, plainStr.Length); Assert.Equal(sourceStr, plainStr); Assert.Equal(sourceBytes.Length, plainBytes.Length); Assert.Equal(sourceBytes, plainBytes); }
public void TestEncodeDecode() { var input = "abcdef 123 a test string baba abba 234"; var dict = CharacterFrequencyDictionary.CreateDictionary(input); var encodeTree = new HuffmanTree <char>(dict); var z = encodeTree.Encode(input); var decodeTree = new HuffmanTree <char>(dict); var decode = decodeTree.Decode(z); Assert.AreEqual(input, decode); }
public void TestEncodeDecode() { var input = "abcdef 123 a test string baba abba 234"; var dict = CharacterFrequencyDictionary.CreateDictionary(input); var encodeTree = new HuffmanTree<char>(dict); var z = encodeTree.Encode(input); var decodeTree = new HuffmanTree<char>(dict); var decode = decodeTree.Decode(z); Assert.AreEqual(input, decode); }
private void button1_Click(object sender, EventArgs e) { int i = 0; richTextBox1.Text = ""; htree.Build(textBox1.Text); encoded = htree.Encode(textBox1.Text); foreach (bool bit in encoded) { richTextBox1.Text += ((bit ? 1 : 0).ToString() + " "); } foreach (KeyValuePair <char, int> item in htree.Frequencies) { richTextBox3.Text += ("Символ: " + item.Key + "\t Кількість: " + item.Value.ToString() + "\t Частота: " + (Math.Round((float)item.Value / textBox1.Text.Length, 3)) + "\t Код " + htree.codec.ToArray()[i] + "\n"); i++; } }
private byte[] Encode(string input) { _tree.BuildTree(input); //Build the huffman tree BitArray encoded = _tree.Encode(input); //Encode the tree //First show the generated binary output //Console.WriteLine(string.Join(string.Empty, encoded.Cast<bool>().Select(bit => bit ? "1" : "0"))); //Next, convert the binary output to the new characterized output string. byte[] bytes = new byte[(encoded.Length / 8) + 1]; encoded.CopyTo(bytes, 0); //string inText = Encoding.ASCII.GetString(bytes); //Console.WriteLine(inText); //Write the compressed output to the textbox. return(bytes); }
private void button7_Click(object sender, EventArgs e) { if (richTextBox7.Text == " ") { MessageBox.Show("Please Enter A Text To Compress"); } else { input = richTextBox7.Text; huffmanTree = new HuffmanTree(); huffmanTree.Build(input); encoded = huffmanTree.Encode(input); richTextBox10.Visible = true; for (int i = 0; i < encoded.Count; i++) { richTextBox10.Text += (encoded[i] ? 1 : 0).ToString(); } } }
public static void CompressHuffman(DownsampleFormat format, string dest) { DownsampleFormat downFormat = format; byte[] data = new byte[format.Ylen + format.Cblen + format.Crlen]; format.data.CopyTo(data, 0); HuffmanTree tree = new HuffmanTree(); tree.CreateTree(tree.GenerateListOfNodes(data)); byte[] decompressDict = tree.SerializeDictionaryToBytes(); byte[] dictionarySize = BitConverter.GetBytes(decompressDict.Length); //svaki integer ima duzinu od 4 bajta u C# byte[] bmpWidth = BitConverter.GetBytes(format.bmpWidth); //4 bajta byte[] bmpHeight = BitConverter.GetBytes(format.bmpHeight); //4 bajta byte[] stride = BitConverter.GetBytes(format.bmpStride); //4 bajta byte[] downsampleChannels = BitConverter.GetBytes(format.code); //4 bajta byte[] YDataLen = BitConverter.GetBytes(format.Ylen); //4 bajta byte[] CbDataLen = BitConverter.GetBytes(format.Cblen); //4 bajta byte[] CrDataLen = BitConverter.GetBytes(format.Crlen); //4 bajta using (var writer = new FileStream(dest, FileMode.Create)) { writer.Write(bmpWidth, 0, bmpWidth.Length); writer.Write(bmpHeight, 0, bmpHeight.Length); writer.Write(stride, 0, stride.Length); writer.Write(downsampleChannels, 0, downsampleChannels.Length); writer.Write(YDataLen, 0, YDataLen.Length); writer.Write(CbDataLen, 0, CbDataLen.Length); writer.Write(CrDataLen, 0, CrDataLen.Length); writer.Write(dictionarySize, 0, dictionarySize.Length); writer.Write(decompressDict, 0, decompressDict.Length); byte[] allData = BitArrayToByteArray(tree.Encode(data)); writer.Write(allData, 0, allData.Length); } }
// Проверка правильности строки для кода Хаффмана public static string CheckString04(string reply, string generated) { try { bool yes = true; string input = generated; if (input.CompareTo("") == 0) { return("Вы не ввели текст!"); } HuffmanTree huffmanTree = new HuffmanTree(); // Строим дерево Хаффмана по весам слов huffmanTree.Build(input); // Кодируем BitArray encoded = (BitArray)huffmanTree.Encode(input); if (huffmanTree.str != reply) { yes = false; } if (yes) { return("Абсолютно верное решение! "); } return("Это не оптимальный код Хаффмана. Вот он: " + huffmanTree.str); } catch (Exception e) { return("Ошибка ввода! " + e.Message); } }
public static FrequencyRecord[] GetFrequencyDictionary(string text) { var result = new List <FrequencyRecord>(); var huffmanTree = new HuffmanTree(); huffmanTree.Build(text); _entropy = 0; for (int i = 0; i < huffmanTree.Frequencies.Count; i++) { var record = new FrequencyRecord(); record._char = huffmanTree.Frequencies.ElementAt(i).Key; record._freq = huffmanTree.Frequencies.ElementAt(i).Value; record._freqPercent = Math.Round(record._freq / ((float)text.Length), 2); foreach (var item in huffmanTree.EncodeChar(record._char)) { record._code += (item ? 1 : 0); } result.Add(record); _entropy += Math.Round((-(result[i]._freqPercent * Math.Log(result[i]._freqPercent, 2))), 2); } BitArray encoded = huffmanTree.Encode(text); Console.Write("Encoded: "); var str = ""; foreach (bool bit in encoded) { str += (bit ? 1 : 0); } _avg = Math.Round((float)str.Length / (float)text.Length, 2); _lenght = str.Length; return(result.ToArray()); }
public void TestEncodeDecodeWithCompression() { var input = "He paused for a moment, many recollections overpowering him. Then he went on telling her the history of his life, unfolding to her the story of his hopes and ambitions, describing to her the very home where he was born, and the dark-eyed sister whom he had loved, and with whom he had played over the daisied fields, and through the carpeted woods, and all among the richly tinted bracken. One day he was told she was dead, and that he must never speak her name; but he spoke it all the day and all the night, Beryl, nothing but Beryl, and he looked for her in the fields and in the woods and among the bracken. It seemed as if he had unlocked the casket of his heart, closed for so many years, and as if all the memories of the past and all the secrets of his life were rushing out, glad to be free once more, and grateful for the open air of sympathy."; var dict = CharacterFrequencyDictionary.CreateDictionary(input); var encodeTree = new HuffmanTree <char>(dict); var encode = encodeTree.Encode(input); var encodeAsByte = CompressUtil.ConvertToByteArray(encode); var secondDict = CharacterFrequencyDictionary.CreateDictionary( dict.GetKeysAsByteArray(), dict.GetValuesAsByteArray()); var encodeAsByteArray = new List <byte>(); foreach (var b in encodeAsByte) { encodeAsByteArray.AddRange(CompressUtil.ConvertToBitArray(b)); } if (encode.Length < encodeAsByteArray.ToArray().Length) { encodeAsByteArray.RemoveRange(encode.Length, encodeAsByteArray.ToArray().Length - encode.Length); } CollectionAssert.AreEqual(dict, secondDict); CollectionAssert.AreEqual(encode, encodeAsByteArray.ToArray()); var decodeTree = new HuffmanTree <char>(secondDict); var decode = decodeTree.Decode(encodeAsByteArray); Assert.AreEqual(input, decode); }
static void Main(string[] args) { Console.WriteLine("Veuillez entrer les éléments de facturation du client :"); string input = Console.ReadLine(); HuffmanTree huffmanTree = new HuffmanTree(); // Construire l'arbre de huffman huffmanTree.Build(input); // Encoder BitArray encoded = huffmanTree.Encode(input); //on retourne le nombre d'octets du message lu au clavier Console.WriteLine(); Console.WriteLine("Votre texte est de " + input.Length + " octets"); //on ouvre une session de connexion sur gmail à travers smtp try { MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); mail.From = new MailAddress("*****@*****.**"); //expéditeur mail.To.Add("*****@*****.**"); //recepteur mail.Subject = "Informations client"; //objet //ic on affiche d'abord le message compréssé chez l'expéditeur Console.WriteLine(); int cpt = 0; //j'initialise un compte ici pour avoir le nombre de bit à la fin de la compression Console.Write("Compressé: "); foreach (bool bit in encoded) { Console.Write((bit ? 1 : 0) + ""); cpt = cpt + 1; } Console.WriteLine(); Console.WriteLine("le texte compréssé est de " + (cpt / 8 + 1) + " octets"); Console.WriteLine(); Console.WriteLine("En cours d'envoi à " + mail.To + "..."); /*foreach (bool bit in encoded) * { * mail.Body = (bit ? 1 : 0) + ""; * } * Console.WriteLine();*/ string chaine; string message = ""; foreach (bool bit in encoded) { chaine = (bit ? 1 : 0) + ""; message = $"{message}{chaine}"; } mail.Body = message; SmtpServer.Port = 587; SmtpServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", "testisj2019"); SmtpServer.EnableSsl = true; Console.WriteLine(); SmtpServer.Send(mail); Console.WriteLine("Votre mail à été envoyé avec succes!!!");//Message succes } catch (Exception ex) { Console.WriteLine(ex.ToString()); } //cette partie du code permet de lire les mails de l'adresse passée en paramètre try { using (Pop3 pop3 = new Pop3()) { pop3.ConnectSSL("pop.gmail.com"); // or ConnectSSL for SSL pop3.Login("*****@*****.**", "mayelle2010"); List <string> uids = pop3.GetAll(); foreach (string uid in uids) { IMail email = new MailBuilder() .CreateFromEml(pop3.GetMessageByUID(uid)); Console.WriteLine(""); Console.WriteLine(email.Date); Console.WriteLine(email.From); Console.WriteLine(email.Subject); } pop3.Close(); } } catch (Limilabs.Client.ServerException e) { Console.WriteLine(e.ToString()); } }
void backWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { System.ComponentModel.BackgroundWorker b = sender as System.ComponentModel.BackgroundWorker; int samples = 32; short[] buffer = new short[samples]; bw = new BinaryWriter(File.Open(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/Code.huf", FileMode.Create)); stream = Bass.BASS_StreamCreateFile(path, 0L, 0L, BASSFlag.BASS_STREAM_DECODE); ww = new WaveWriter(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/HufSound.wav", stream, true); int mult = 0; long len = Bass.BASS_ChannelGetLength(stream, BASSMode.BASS_POS_BYTES); while (Bass.BASS_ChannelIsActive(stream) == BASSActive.BASS_ACTIVE_PLAYING) { int length = Bass.BASS_ChannelGetData(stream, buffer, samples * 2); mult++; b.ReportProgress((int)(((samples * mult) * 100) / len * 2)); List <short> listBuffer = new List <short>(); HuffmanTree tree = new HuffmanTree(); if (length > 0) { listBuffer.AddRange(buffer); short[] auxbuf = new short[buffer.Length]; auxbuf = buffer; canvasWavComp.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.SystemIdle, new Action(delegate { //Whole Wave //double xScale = canvasWavComp.Width / samples; //Formula by Manuel García. Dude you're amazing. //NOTE: multiply by 2 'cos I supoused some relation with Nyquist Theorem double xScale = (canvasWavComp.Width * samples) / len * 2; double yScale = (canvasWavComp.Height / (double)(amplitude * 2)) * ((double)amplitude / MAX_AMP); Polyline graphLine = new Polyline(); //This Line is used to move on the x axis Canvas.SetLeft(graphLine, xAxis); graphLine.Stroke = new SolidColorBrush(Color.FromRgb(244, 67, 54)); graphLine.StrokeThickness = 2; for (int i = 0; i < buffer.Length; i++) { graphLine.Points.Add(new Point(xScale * i, (canvasWavComp.Height / 2) - (buffer[i] * yScale))); } xAxis += xScale; //canvasWavComp.Children.Clear(); canvasWavComp.Children.Add(graphLine); })); double entaux = 0; foreach (var sym in listBuffer.GroupBy(i => i)) { NodeHuf nodeHuf = new NodeHuf(); nodeHuf.Symbol = sym.Key; nodeHuf.Frequency = sym.Count(); nodeHuf.Right = nodeHuf.Left = null; tree.Add(nodeHuf); double prob = (double)nodeHuf.Frequency / samples; //entropy -= prob * (Math.Log(prob) / Math.Log(2)); entaux += prob * Math.Log(1 / (prob), 2); entauxlbl = entaux; } entropy += entaux; entcount++; tree.Build(); //Encode System.Collections.BitArray encoded = tree.Encode(auxbuf); byte[] arrayBytes = new byte[encoded.Length / 8 + (encoded.Length % 8 == 0 ? 0 : 1)]; encoded.CopyTo(arrayBytes, 0); File.WriteAllBytes("Compress.bin", arrayBytes); //Decode byte[] data; Stream fs = File.OpenRead("Compress.bin"); data = new byte[fs.Length]; fs.Read(data, 0, data.Length); System.Collections.BitArray bitDec = new System.Collections.BitArray(data); short[] decoded = tree.Decode(bitDec); if (decoded.Length > 0) { ww.Write(decoded, length); } bw.Write(data); fs.Close(); } } //Delete temporaly file File.Delete("Compress.bin"); //Close de Stream WAV ww ww.Close(); //If you not add this line, the backgroundworker will be restat but when file is create again //there will be an incongruence because the bw never was closed. bw.Close(); entropy /= entcount;// (len / samples); entcount = 0; }
static void Main(string[] args) { int action; string inputFilePath; string inputFileName; string outputFileName; int.TryParse(args[0], out action); if (args.Length < 4 || (args.Length == 4 && action != 1 && action != 2)) { action = 0; Console.WriteLine("Please choose option:"); Console.WriteLine("1 - encode"); Console.WriteLine("2 - decode"); string option = Console.ReadLine(); action = int.Parse(option); while (action != 1 && action != 2) { Console.WriteLine("there is no such option"); Console.WriteLine("1 - encode"); Console.WriteLine("2 - decode"); option = Console.ReadLine(); action = int.Parse(option); } Console.WriteLine("Please enter the full path of the input file"); inputFilePath = Console.ReadLine(); Console.WriteLine("Please enter the name of the input file"); inputFileName = Console.ReadLine(); Console.WriteLine("Please enter the name of the output file"); outputFileName = Console.ReadLine(); } else { action = int.Parse(args[0]); inputFilePath = args[1]; inputFileName = args[2]; outputFileName = args[3]; } string inputFileFullName = inputFilePath + "\\" + inputFileName; string outputFileFullName = inputFilePath + "\\" + outputFileName; bool isSucceeded; if (action == 1 || action == 2) { if (action == 1) { isSucceeded = HuffmanTree.Encode(inputFileFullName, outputFileFullName); } else { isSucceeded = HuffmanTree.Decode(inputFileFullName, outputFileFullName); } Console.WriteLine(isSucceeded ? "The operation was successful" : "Operation failed, check if the input file exist"); } }
private void buttonRun_Click(object sender, EventArgs e) { //Сначала для классического алгритма if (textBoxOutC.Text != "") { labelOutС.Enabled = true; textBoxOutC.Enabled = true; //получаем частотный словарь FrequencyDictionary frequencyDictionary = new FrequencyDictionary(openFileDialogInput.FileName); SizeDictionaryC = frequencyDictionary.CountWord; textBoxSizeDictionaryС.Text = SizeDictionaryC.ToString() + " слов"; //построение дерева var startTime = System.Diagnostics.Stopwatch.StartNew(); HuffmanTree huffmanTree = new HuffmanTree(frequencyDictionary); startTime.Stop(); var resultTime = startTime.Elapsed.TotalSeconds; //string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:000}", // resultTime.Hours, // resultTime.Minutes, // resultTime.Seconds, // resultTime.Milliseconds); textBoxTimeBuildTree.Text = resultTime.ToString(); //Кодирование startTime = System.Diagnostics.Stopwatch.StartNew(); huffmanTree.Encode(@openFileDialogInput.FileName, @textBoxOutC.Text); startTime.Stop(); resultTime = resultTime + startTime.Elapsed.TotalSeconds; //elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:000}", // resultTime.Hours, // resultTime.Minutes, // resultTime.Seconds, // resultTime.Milliseconds); textBoxSpeedEncodeС.Text = resultTime.ToString(); //сбрасываем дерево huffmanTree = new HuffmanTree(); //Декодируем startTime = System.Diagnostics.Stopwatch.StartNew(); huffmanTree.Decode(@textBoxOutC.Text, @textBoxDecodeFileC.Text); startTime.Stop(); resultTime = startTime.Elapsed.TotalSeconds; //elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:000}", // resultTime.Hours, // resultTime.Minutes, // resultTime.Seconds, // resultTime.Milliseconds); textBoxSpeedDecodeС.Text = resultTime.ToString(); //Получаем другие статитстики SizeFileEncodeC = new FileInfo(@textBoxOutC.Text).Length; textBoxSizeCompressС.Text = SizeFileEncodeC.ToString() + " байт"; textBoxCoefficientCompressС.Text = ((SizeFileInput * 1.0) / SizeFileEncodeC).ToString(); groupBoxClassicHuffmanAlgo.Enabled = true; } //Потом для адаптивного if (textBoxOutA.Text != "") { labelOutA.Enabled = true; textBoxOutA.Enabled = true; HuffmanAdaptiveTree huffmanAdaptiveTree = new HuffmanAdaptiveTree(); //Кодирование var startTime = System.Diagnostics.Stopwatch.StartNew(); huffmanAdaptiveTree.Encode(@openFileDialogInput.FileName, @textBoxOutA.Text); startTime.Stop(); var resultTime = startTime.Elapsed.TotalSeconds; //var elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:000}", // resultTime.Hours, // resultTime.Minutes, // resultTime.Seconds, // resultTime.Milliseconds); textBoxSpeedEncodeA.Text = resultTime.ToString(); //сбрасываем дерево huffmanAdaptiveTree = new HuffmanAdaptiveTree(); huffmanAdaptiveTree.Reset(); //Декодируем startTime = System.Diagnostics.Stopwatch.StartNew(); huffmanAdaptiveTree.Decode(@textBoxOutA.Text, @textBoxDecodeFileA.Text); startTime.Stop(); resultTime = startTime.Elapsed.TotalSeconds; //elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:000}", // resultTime.Hours, // resultTime.Minutes, // resultTime.Seconds, // resultTime.Milliseconds); textBoxSpeedDecodeA.Text = resultTime.ToString(); //Получаем другие статитстики SizeFileEncodeA = new FileInfo(@textBoxOutA.Text).Length; textBoxSizeCompressA.Text = SizeFileEncodeA.ToString() + " байт"; textBoxCoefficientCompressA.Text = ((SizeFileInput * 1.0) / SizeFileEncodeA).ToString(); groupBoxAdaptiveHuffmanAlgo.Enabled = true; } }