如何比较2个字节的数组? [英] How to compare 2 byte arrays?
问题描述
我有一个问题,我正在为比赛设计一个应用程序,并且其中一个主要功能需要比较2个字节的数组.但是我无法单独比较每个数组元素,因为两个数组都具有13000个以上的元素,而且它们不一定按相同的顺序排列.我需要将它们作为一个整体进行比较,并返回它们相互匹配的百分比.
有人有什么想法吗?
I have a problem, i am designing an app for a competition, and one of the main functions requires a comparison of 2 byte arrays. But I cannot compare each array element individually as both of the arrays have more than 13000 elements and they are not nessecarily in the same order. I need to compare them as a whole, and return a percentage of how much they match each other.
Does anyone have any ideas?
Thank you in advance!
推荐答案
您可以为此使用SequenceEqual
.
http://msdn.microsoft.com/en-us/library/bb348567.aspx
祝你好运!
You can useSequenceEqual
for that.
http://msdn.microsoft.com/en-us/library/bb348567.aspx
Good luck!
一个想法:
Just an idea:
int[] bucket = new int[256];
foreach ( var b in array1 )
{
bucket[b]++;
}
foreach ( var b in array2 )
{
bucket[b]--;
}
double percent = 100;
for ( int i = 0; i < 256; ++i )
{
double val = 100 * ((double)bucket[i] / array1.Length);
percent -= Math.Abs( val );
}
Console.Out.WriteLine( string.Format( "array1 equals array2 to {0}%", percent ) );
数组bucket
跟踪每个源数组中存在多少个不同的字节.
正值表示array1
中的字节比array2
中的字节多x倍.反之则为负值.
最后,您可以轻松计算百分比. (至少这是它在我疯狂的大脑中应该如何工作的方法;))
The array bucket
keeps track of how many different bytes are present in each of the source arrays.
A positive value means that a byte is x time more often in array1
than in array2
. A negative value the other way around.
At the end you can calculate the percentage easily. (At least that''s how it should work in my crazy brain ;))
假设您有两个数组,并且按位置进行比较,则可以使用以下内容:
Assuming you have two arrays and you compare by position, then you might use the following:
byte[] a = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
byte[] b = new byte[] { 0, 1, 2, 3, 3, 3, 6, 7 };
int n = Math.Min(a.Length, b.Length);
int m = Math.Max(a.Length, b.Length);
int c = 0;
a.Take(n).Aggregate(0, (i, e) => { if (e == b[i++]) c++; return i; });
Console.WriteLine("Match = {0} = {1}%", c, 100.0 * c / m);
这篇关于如何比较2个字节的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!