AiSD.Laba2/HuffmanCode/Algoritm.cs
2023-04-27 16:15:28 +04:00

74 lines
2.0 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace HuffmanCode
{
internal class Algoritm
{
Node root = null;
Dictionary<char, string> characters = new Dictionary<char, string>();
public void work(string data)
{
var charDict = new Dictionary<char, int>();
for (int i = 0; i < data.Length; i++)
{
if (charDict.ContainsKey(data[i]))
{
charDict[data[i]]++;
}
else
{
charDict.Add(data[i], 1);
}
}
List<Node> nodes = new List<Node>();
foreach (var item in charDict)
{
nodes.Add(new Node() { Character = item.Key.ToString(), Count = item.Value });
}
nodes.Sort();
while (nodes.Count != 1)
{
var tempNode = new Node();
tempNode.Character = nodes[0].Character + nodes[1].Character;
//нужно чтобы сложило две буквы в одно
tempNode.Count = nodes[0].Count + nodes[1].Count;
tempNode.Left = nodes[0];
tempNode.Right = nodes[1];
nodes.RemoveAt(0);
nodes.RemoveAt(0);
nodes.Add(tempNode);
nodes.Sort();
}
root = nodes[0];
MyEncode(root);
//TODO: красиво вывести
}
protected void MyEncode(Node node, string code = "")
{
if (node.Character.Length == 1)
{
characters.Add(node.Character[0], code);
}
else
{
MyEncode(node.Left, code + "0");
MyEncode(node.Right, code + "1");
}
}
}
}