Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace Фано_Шеннон
- {
- internal class Program
- {
- static void Main(string[] args)
- {
- double[] prob;
- char[] chars;
- string stroka = "";
- FanoShennon fs;
- Dictionary<char, string> dict = new Dictionary<char, string>();
- Dictionary<string, char> reversedict = new Dictionary<string, char>();
- using(var sr = new StreamReader("input.txt"))
- {
- string[] str = sr.ReadToEnd().Split('\n');
- int n = str.Length;
- prob = new double[str.Length-1]; chars = new char[str.Length-1];
- for (int i = 0; i < str.Length-1; i++)
- {
- string[] vs = str[i].Split(new char[] {'\r', ' '});
- prob[i] = double.Parse(vs[0]);
- chars[i] = char.Parse(vs[1]);
- }
- stroka = str[str.Length-1];
- Console.WriteLine(stroka);
- fs = new FanoShennon(prob, chars);
- fs.Sort();
- fs.Fano(0,n-2);
- for (int i = 0; i < n-1; i++)
- {
- dict.Add(fs.let[i], fs.Res[i]);
- reversedict.Add(fs.Res[i], fs.let[i]);
- Console.WriteLine(fs.let[i] + " " + fs.Res[i]);
- }
- }
- string codeStr = "";
- for (int i = 0; i < stroka.Length; i++)
- {
- codeStr += dict[stroka[i]];
- }
- Console.WriteLine(codeStr);
- double step = Math.Round((double)stroka.Length * 8 / codeStr.Length,4);
- Console.WriteLine($"Степень сжатия = {step}");
- string tempstr = "";
- string result = "";
- for (int i = 0; i < codeStr.Length; i++)
- {
- tempstr += codeStr[i];
- if(reversedict.ContainsKey(tempstr))
- {
- result += reversedict[tempstr];
- tempstr = "";
- }
- }
- Console.WriteLine(result);
- Console.ReadKey();
- }
- }
- class FanoShennon
- {
- public FanoShennon(double[] p, char[] letters)
- {
- prob = p;
- let = letters;
- Res = new string[prob.Length];
- }
- double[] prob;
- internal char[] let;
- internal string[] Res;
- double schet1 = 0;
- double schet2 = 0;
- public void Sort()
- {
- for (int i = 0; i < prob.Length; i++)
- {
- for (int j = 0; j < prob.Length - i - 1; j++)
- {
- if (prob[j] < prob[j + 1])
- {
- char temp2;
- double temp1 = 0;
- temp1 = prob[j];
- temp2 = let[j];
- prob[j] = prob[j + 1];
- let[j] = let[j + 1];
- prob[j + 1] = temp1;
- let[j + 1] = temp2;
- }
- }
- }
- }
- int m;
- public int Delenie_Posledovatelnosty(int L, int R)
- {
- schet1 = 0;
- for (int i = L; i <= R - 1; i++)
- {
- schet1 = schet1 + prob[i];
- }
- schet2 = prob[R];
- m = R;
- while (schet1 >= schet2)
- {
- m = m - 1;
- schet1 = schet1 - prob[m];
- schet2 = schet2 + prob[m];
- }
- return m;
- }
- public void Fano(int L, int R)
- {
- int n;
- if (L < R)
- {
- n = Delenie_Posledovatelnosty(L, R);
- //Console.WriteLine(n);
- for (int i = L; i <= R; i++)
- {
- if (i <= n) Res[i] += Convert.ToByte(0);
- else Res[i] += Convert.ToByte(1);
- }
- Fano(L, n);
- Fano(n + 1, R);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement