forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BurrowsWheelerTransform.cs
72 lines (62 loc) · 2.28 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
using System;
using System.Linq;
namespace Algorithms.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>
public class BurrowsWheelerTransform
{
/// <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 (string encoded, int index) Encode(string s)
{
if (s.Length == 0)
{
return (string.Empty, 0);
}
var rotations = GetRotations(s);
Array.Sort(rotations, StringComparer.Ordinal);
var lastColumn = rotations
.Select(x => x[x.Length - 1])
.ToArray();
var encoded = new string(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>
public string Decode(string s, int index)
{
if (s.Length == 0)
{
return string.Empty;
}
var rotations = new string[s.Length];
for (var i = 0; i < s.Length; i++)
{
for (var j = 0; j < s.Length; j++)
{
rotations[j] = s[j] + rotations[j];
}
Array.Sort(rotations, StringComparer.Ordinal);
}
return rotations[index];
}
private string[] GetRotations(string s)
{
var result = new string[s.Length];
for (var i = 0; i < s.Length; i++)
{
result[i] = s.Substring(i) + s.Substring(0, i);
}
return result;
}
}
}