❔ Troubles getting all Largest Common Subsequences of two strings.
For fun trying to write a system to take differential backups of strings.
The backbone is this method I wrote, which should find all LCSs between two strings:
The backbone is this method I wrote, which should find all LCSs between two strings:
public static List<Tuple<int, int, int>> GetAllLCS(string _new, string _old)
{
List<Tuple<int, int, int>> _matches = new List<Tuple<int, int, int>>(); // Get all common substrings
for (int i = 0; i < _new.Length; i++)
{
for (int j = _new.Length; j > i; j--)
{
var o = _old.IndexOf(_new.Substring(i, j - i));
if (o != -1)
{
_matches.Add(Tuple.Create(i, j, o));
}
}
}
_matches.Sort(new Comparison<Tuple<int,int,int>>((x, y) => { // Sort them from largest to smallest substrings
return (x.Item2 - x.Item1)-(y.Item2 - y.Item1);
}));
var _outmatches = new List<Tuple<int, int, int>>();
foreach (var i in _matches) // Duplicate the list
{
_outmatches.Add(i);
}
foreach (var i in _matches) // Remove any substrings that overlap
{
foreach (var j in _matches)
{
if (i == j) continue;
if ((j.Item1 > i.Item1 && j.Item1 < i.Item2 - 1) || (j.Item2 > i.Item1 && j.Item2 < i.Item2 - 1)) _outmatches.Remove(j);
}
}
return _outmatches;
} public static List<Tuple<int, int, int>> GetAllLCS(string _new, string _old)
{
List<Tuple<int, int, int>> _matches = new List<Tuple<int, int, int>>(); // Get all common substrings
for (int i = 0; i < _new.Length; i++)
{
for (int j = _new.Length; j > i; j--)
{
var o = _old.IndexOf(_new.Substring(i, j - i));
if (o != -1)
{
_matches.Add(Tuple.Create(i, j, o));
}
}
}
_matches.Sort(new Comparison<Tuple<int,int,int>>((x, y) => { // Sort them from largest to smallest substrings
return (x.Item2 - x.Item1)-(y.Item2 - y.Item1);
}));
var _outmatches = new List<Tuple<int, int, int>>();
foreach (var i in _matches) // Duplicate the list
{
_outmatches.Add(i);
}
foreach (var i in _matches) // Remove any substrings that overlap
{
foreach (var j in _matches)
{
if (i == j) continue;
if ((j.Item1 > i.Item1 && j.Item1 < i.Item2 - 1) || (j.Item2 > i.Item1 && j.Item2 < i.Item2 - 1)) _outmatches.Remove(j);
}
}
return _outmatches;
}