-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLZ78.cs
More file actions
89 lines (74 loc) · 2.59 KB
/
Copy pathLZ78.cs
File metadata and controls
89 lines (74 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System.Collections.Generic;
using System.Linq;
namespace CodingTheory
{
public class LZ78 : IAlgorithm
{
private double _compressionRatio = -1;
private Dictionary<string, int> dictionary = new Dictionary<string, int>();
public string GetName()
{
return "Словарный метод сжатия LZ78";
}
public string Encode(string input)
{
_compressionRatio = -1;
dictionary = new Dictionary<string, int>();
string output = string.Empty;
int nextNumber = 1;
int inputLength = input.Length;
while (input != string.Empty)
{
string substr = string.Empty;
for (var i = 0; i < input.Length; i++)
{
substr += input[i];
if (!dictionary.ContainsKey(substr))
break;
}
if (!dictionary.ContainsKey(substr))
dictionary.Add(substr, nextNumber++);
input = input.Substring(substr.Length, input.Length - substr.Length);
if (substr.Length == 1)
output += '0' + substr;
else
{
int number = dictionary[substr.Substring(0, substr.Length - 1)];
output += number.ToString() + substr[substr.Length - 1];
}
}
_compressionRatio = (double)output.Length / inputLength;
dictionary = new Dictionary<string, int>();
return output;
}
public string Decode(string input)
{
string stringCount = string.Empty;
string output = string.Empty;
int nextNumber = 1;
foreach (char ch in input)
{
if (char.IsDigit(ch))
{
stringCount += ch.ToString();
continue;
}
int n = int.Parse(stringCount);
string substr;
if (n == 0)
substr = string.Format("{0}", ch);
else
substr = dictionary.FirstOrDefault(x => x.Value == n).Key + ch;
if (!dictionary.ContainsKey(substr))
dictionary.Add(substr, nextNumber++);
output += substr;
stringCount = "";
}
return output;
}
public double GetCompressionRatio()
{
return _compressionRatio;
}
}
}