Advertisement
myloyo

доп задача код хаффмана

May 23rd, 2024
584
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 9.53 KB | None | 0 0
  1. //код хаффамана класс
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.ComponentModel;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Runtime.InteropServices;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11.  
  12. namespace Myloyorrrr
  13. {
  14.     internal class HuffmanTree
  15.     {
  16.         private class Node:IComparable<Node>
  17.         {
  18.             public char symb; //информационное поле
  19.             public int count; //кол-во появлений в строке
  20.             public int height; // высота в дереве
  21.             public Node left; //ссылка на левое поддерево
  22.             public Node right; //ссылка на правое поддерево
  23.  
  24.             //конструктор вложенного класса, создает узел дерева
  25.             public Node(char x, int y, int z)
  26.             {
  27.                 symb = x;
  28.                 count = y;
  29.                 height = z;
  30.                 left = null;
  31.                 right = null;
  32.                
  33.             }
  34.            
  35.             public Node(char s, int c, int h, Node l, Node r)
  36.             {
  37.                 symb = s;
  38.                 count = c;
  39.                 height = h;
  40.                 left = l;
  41.                 right = r;
  42.             }
  43.  
  44.             public int CompareTo(Node node)
  45.             {
  46.                 if (this.count == node.count)
  47.                 {
  48.                     if (this.height == node.height)
  49.                     {
  50.                         return this.symb.CompareTo(node.symb);
  51.                     }
  52.                     return this.height.CompareTo(node.height);
  53.                 }
  54.                 return this.count.CompareTo(node.count);
  55.             }
  56.  
  57.         }
  58.         Node tree;
  59.         Dictionary<char, string> encodeDict = new Dictionary<char, string>();
  60.         Dictionary<string, char> decodeDict = new Dictionary<string, char>();
  61.  
  62.  
  63.         private void Coding(Node node, string code)
  64.         {
  65.             if (node == null)
  66.             {
  67.                 return;
  68.             }
  69.             if (node.right == null && node.left == null)
  70.             {
  71.                 encodeDict[node.symb] = code;
  72.             }
  73.             //if (node.right != null)
  74.             //{
  75.             //    Coding(node.right, code + "1");
  76.             //}
  77.             //if (node.left != null)
  78.             //{
  79.             //    Coding(node.left, code + "0");
  80.             //}
  81.             Coding(node.left, code + "0");
  82.             Coding(node.right, code + "1");
  83.         }
  84.  
  85.         public void Encode(string fileinname, string fileoutname)
  86.         {
  87.             string s = "";
  88.             using (StreamReader f = new StreamReader(fileinname))
  89.             {
  90.                 s = f.ReadToEnd();
  91.             }
  92.  
  93.             Dictionary<char, int> symbols = new Dictionary<char, int>();
  94.  
  95.             foreach(var elem in s)
  96.             {
  97.                 if (!symbols.ContainsKey(elem))
  98.                 {
  99.                     symbols.Add(elem, 0);
  100.                 }
  101.                 symbols[elem]++;
  102.             }
  103.  
  104.             SortedSet<Node> nodes = new SortedSet<Node>();
  105.  
  106.             foreach(var node in symbols)
  107.             {
  108.                 nodes.Add(new Node(node.Key, node.Value, 1));
  109.             }
  110.  
  111.             while (nodes.Count > 1)
  112.             {
  113.                 Node Node1 = nodes.First();
  114.                 nodes.Remove(Node1);
  115.                 Node Node2 = nodes.First();
  116.                 nodes.Remove(Node2);
  117.                 Node New_Node = new Node(Node1.symb, Node1.count + Node2.count, Math.Max(Node1.height, Node2.height) + 1, Node1, Node2);
  118.                 nodes.Add(New_Node);
  119.                
  120.  
  121.             }
  122.  
  123.             tree = nodes.First();
  124.             Coding(tree, "");
  125.  
  126.             foreach(var node in encodeDict)
  127.             {
  128.                 Console.WriteLine(node.Key + " = " + node.Value);
  129.             }
  130.  
  131.             int size = 0;
  132.             foreach(var x in s)
  133.             {
  134.                 size += encodeDict[x].Length;
  135.             }
  136.  
  137.             BitArray codes = new BitArray(size);
  138.             int ind = 0;
  139.             foreach(var x in s)
  140.             {
  141.                 string code = encodeDict[x];
  142.                 for (int i = 0; i < code.Length; i++)
  143.                 {
  144.                     codes[ind] = (code[i] == '1');
  145.                     ind++;
  146.                 }
  147.             }
  148.  
  149.             byte[] bytes = new byte[(size+7)/8];
  150.             codes.CopyTo(bytes, 0);
  151.  
  152.             using (BinaryWriter f = new BinaryWriter(File.Open(fileoutname, FileMode.Create)))
  153.             {
  154.                 f.Write(encodeDict.Count);
  155.                 foreach(var node in encodeDict)
  156.                 {
  157.                     f.Write(node.Key);
  158.                     f.Write(node.Value);
  159.                 }
  160.                 f.Write(size);
  161.                 f.Write(bytes);
  162.             }
  163.         }
  164.  
  165.  
  166.         public void Decode(string fileinname, string fileoutname)
  167.         {
  168.             int count = 0;
  169.             StringBuilder res = new StringBuilder();
  170.             using (BinaryReader f = new BinaryReader(File.Open(fileinname, FileMode.Open)))
  171.             {
  172.                 count = f.ReadInt32();
  173.                 for (int i = 0; i < count; i++)
  174.                 {
  175.                     char symb = f.ReadChar();
  176.                     string s = f.ReadString();
  177.                     decodeDict[s] = symb;
  178.                 }
  179.  
  180.                 int size = f.ReadInt32();
  181.                 BitArray bits = new BitArray(size);
  182.                 int ind = 0;
  183.                 for (int i = 0; i < (size+7)/8; i++)
  184.                 {
  185.                     byte b = f.ReadByte();
  186.                     for (int j = 0; j < 8; j++)
  187.                     {
  188.                         bits[ind] = ((b >> j) & 1) == 1;
  189.                         ind++;
  190.                         if (ind >= size)
  191.                         {
  192.                             break;
  193.                         }
  194.                     }
  195.                 }
  196.                 string temp = "";
  197.                 for (int i = 0; i < size; i++)
  198.                 {
  199.                     temp += (bits[i]) ? "1": "0";
  200.                     if (decodeDict.ContainsKey(temp))
  201.                     {
  202.                         res.Append(decodeDict[temp]);
  203.                         temp = "";
  204.                     }
  205.  
  206.                 }
  207.  
  208.             }
  209.  
  210.             using(StreamWriter f = new StreamWriter(fileoutname))
  211.             {
  212.                 f.Write(res.ToString());
  213.             }
  214.         }
  215.     }
  216. }
  217.  
  218. //основная прога
  219. using System;
  220. using System.IO;
  221.  
  222. namespace Myloyorrrr
  223. {
  224.     internal class Program
  225.     {
  226.         static void Main()
  227.         {
  228.             //Graph G = new Graph("C:/Настя/книит/in.txt");
  229.             //G.Show();
  230.             //Console.WriteLine();
  231.             //
  232.             ////3 задача
  233.             //Console.WriteLine("Введите первую вершину:");
  234.             //int a = int.Parse(Console.ReadLine());
  235.             //Console.WriteLine("Введите вторую вершину:");
  236.             //int b = int.Parse(Console.ReadLine());
  237.             //Console.WriteLine("Введите вершину, через которую нельзя пройти:");
  238.             //int d = int.Parse(Console.ReadLine());
  239.             //Console.WriteLine();
  240.             //G.Myloyo_find(a-1, b-1, d-1);
  241.  
  242.  
  243.             //// 1 задача: подсчитать смежные вершины с данной вершиной
  244.             //Console.Write("Введите номер вершины: ");
  245.             //int v = int.Parse(Console.ReadLine());
  246.             //G.Adjacent(v);
  247.  
  248.             //// 2 задача: определить все пары вершин, для которых существует путь длиной не более L
  249.             //Console.Write("Введите требуемую длину пути: ");
  250.             //int L = int.Parse(Console.ReadLine());
  251.             //G.Floyd_new(L);
  252.  
  253.             //BinaryTree lipa = new BinaryTree();
  254.             //int n = 0;
  255.  
  256.             ////Чтение последовательности чисел из файла input.txt и добавление их в дерево
  257.             //using (StreamReader f = new StreamReader("C:/Настя/книит/in.txt"))
  258.             //{
  259.             //    string line;
  260.             //    while ((line = f.ReadLine()) != null)
  261.             //    {
  262.             //        string[] text = line.Split(' ');
  263.             //        for (int i = 0; i < text.Length; i++)
  264.             //        {
  265.             //            int num = int.Parse(text[i]);
  266.             //            lipa.Add(num);
  267.             //            n++;
  268.             //        }
  269.             //    }
  270.  
  271.             //}
  272.  
  273.             //lipa.Preorder();
  274.  
  275.             ////3 деревья
  276.             //bool IsBalance = lipa.Balance();
  277.             //if (IsBalance)
  278.             //{
  279.             //    Console.WriteLine("Дерево является сбалансированным");
  280.             //}
  281.             //else
  282.             //{
  283.             //    Console.WriteLine("Дерево не является сбалансированным");
  284.             //}
  285.  
  286.             //доп задача
  287.             HuffmanTree tree = new HuffmanTree();
  288.             //tree.Encode("C:/Настя/книит/in.txt", "C:/Настя/книит/out.dat");
  289.             tree.Decode("C:/Настя/книит/out.dat", "C:/Настя/книит/out.txt");
  290.  
  291.         }
  292.     }
  293. }
  294.  
  295.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement