我决定使用列表,而不是数组,因为它有更多此类操作的助手。据我了解深度=每个数组中必须相等的项目数量。这个有效,看看这个:
class Program
{
static void Main(string[] args)
{
List<byte> b = new List<byte>() { 50, 60, 70, 80, 90, 10, 20, 1, 2, 3, 4, 5, 50, 2, 3, 1, 2, 3, 4, 5 };
List<byte> b2 = new List<byte>() { 1, 2, 3, 4, 5 };
SmartComparer comparer = new SmartComparer();
//Setting the depth here, now the depth is = 5
var result = comparer.CompareArraysWithDepth(b, b2, 5);
foreach (var keyValuePair in result)
{
Console.WriteLine(String.Format("b[{0}]->b[{1}] are equal to b2[{2}]->b2[{3}]", keyValuePair.Key.Key,
keyValuePair.Key.Value, keyValuePair.Value.Key, keyValuePair.Value.Value));
}
}
}
public class SmartComparer
{
public Boolean CompareRange(List<byte> a, List<byte> b)
{
for (int i = 0; i < a.Count; i++)
{
if (a[i] != b[i])
{
return false;
}
}
return true;
}
/// <summary>
/// |
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="depth"></param>
/// <returns>Key->range in 'a', Value->range in 'b'</returns>
public List<KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>>> CompareArraysWithDepth(
List<byte> a, List<byte> b, int depth)
{
var result = new List<KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>>>();
if (depth > b.Count)
throw new ArgumentException("Array 'b' item count should be more then depth");
if(a.Count<b.Count)
throw new ArgumentException("Array 'a' item count should be more then Array 'b' item count");
for (int i = 0; i <= a.Count - depth; i++)
{
for (int j = 0; j <= b.Count - depth; j++)
{
if (CompareRange(a.GetRange(i, depth), b.GetRange(j, depth)))
{
result.Add(new KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>>(new KeyValuePair<int, int>(i, i + depth-1), new KeyValuePair<int, int>(j, j + depth-1)));
}
}
}
return result;
}
}
添加
对于深度 = 3,此操作的结果:
b[7]->b[9] are equal to b2[0]->b2[2]
b[8]->b[10] are equal to b2[1]->b2[3]
b[9]->b[11] are equal to b2[2]->b2[4]
b[15]->b[17] are equal to b2[0]->b2[2]
b[16]->b[18] are equal to b2[1]->b2[3]
b[17]->b[19] are equal to b2[2]->b2[4]
对于深度 = 2,此操作的结果:
b[7]->b[8] are equal to b2[0]->b2[1]
b[8]->b[9] are equal to b2[1]->b2[2]
b[9]->b[10] are equal to b2[2]->b2[3]
b[10]->b[11] are equal to b2[3]->b2[4]
b[13]->b[14] are equal to b2[1]->b2[2]
b[15]->b[16] are equal to b2[0]->b2[1]
b[16]->b[17] are equal to b2[1]->b2[2]
b[17]->b[18] are equal to b2[2]->b2[3]
b[18]->b[19] are equal to b2[3]->b2[4]
对于深度 = 5,此操作的结果:
b[7]->b[11] are equal to b2[0]->b2[4]
b[15]->b[19] are equal to b2[0]->b2[4]