- Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathBurrowsWheelerTransform.cs
73 lines (62 loc) · 2.08 KB
/
BurrowsWheelerTransform.cs
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
usingSystem;
usingSystem.Linq;
namespaceAlgorithms.DataCompression;
/// <summary>
/// The Burrows–Wheeler transform (BWT) rearranges a character string into runs of similar characters.
/// This is useful for compression, since it tends to be easy to compress a string that has runs of repeated
/// characters.
/// See <a href="https://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transform">here</a> for more info.
/// </summary>
publicclassBurrowsWheelerTransform
{
/// <summary>
/// Encodes the input string using BWT and returns encoded string and the index of original string in the sorted
/// rotation matrix.
/// </summary>
/// <param name="s">Input string.</param>
public(stringEncoded,intIndex)Encode(strings)
{
if(s.Length==0)
{
return(string.Empty,0);
}
varrotations=GetRotations(s);
Array.Sort(rotations,StringComparer.Ordinal);
varlastColumn=rotations
.Select(x =>x[^1])
.ToArray();
varencoded=newstring(lastColumn);
return(encoded,Array.IndexOf(rotations,s));
}
/// <summary>
/// Decodes the input string and returns original string.
/// </summary>
/// <param name="s">Encoded string.</param>
/// <param name="index">Index of original string in the sorted rotation matrix.</param>
publicstringDecode(strings,intindex)
{
if(s.Length==0)
{
returnstring.Empty;
}
varrotations=newstring[s.Length];
for(vari=0;i<s.Length;i++)
{
for(varj=0;j<s.Length;j++)
{
rotations[j]=s[j]+rotations[j];
}
Array.Sort(rotations,StringComparer.Ordinal);
}
returnrotations[index];
}
privatestring[]GetRotations(strings)
{
varresult=newstring[s.Length];
for(vari=0;i<s.Length;i++)
{
result[i]=s.Substring(i)+s.Substring(0,i);
}
returnresult;
}
}