我有Bitarray数组(每个元素由128位组成),我想找到它的每个元素的重复。
我试过这段代码:
for (int i = 0; i < final.Length; i++)
{
final[i] = BitArrayToStr(sub_string[i]);
}
var duplicates = final
.GroupBy(s => s)
.Where(g => g.Count() > 1)
.Select(g => g.Key);
var dict = new Dictionary<string,int>();
foreach (var num in final)
{
if (!dict.ContainsKey(num))
{
dict.Add(num, 0);
}
dict[num]++;
}
bool dup=false;
foreach (var kvp in dict)
{
if (kvp.Value != 1)
{
Console.WriteLine("{0} repeats {1} times", kvp.Key, kvp.Value);
dup = true;
}
}
if (dup == false)
{ Console.WriteLine("NO DUPLICATE"); }
Console.WriteLine("END");
static String BitArrayToStr(BitArray ba) //**** **** convert bit
array to string of chars ****
{
byte[] strArr = new byte[ba.Length / 8];
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
for (int i = 0; i < ba.Length / 8; i++)
{
for (int index = i * 8, m = 1; index < i * 8 + 8; index++, m *= 2)
{
strArr[i] += ba.Get(index) ? (byte)m : (byte)0;
}
}
return encoding.GetString(strArr);
}
但我不想将其转换为字符串,因为结果将是假的
我想知道bitarray数组的每个元素的重复。
有人可以帮忙吗?
答案 0 :(得分:0)
将BitArray转换为1s和0s的字符串非常容易:
static public string ToBitString(this BitArray This)
{
return string.Join("", This.Cast<bool>().Select( bit => bit ? 1 : 0 ));
}
有了这些知识,我们可以为BitArray编写一个EqualityComparer,如下所示:
public class BitArrayComparer : IEqualityComparer<BitArray>
{
public bool Equals(BitArray a, BitArray b)
{
return a.ToBitString() == b.ToBitString();
}
public int GetHashCode(BitArray o)
{
return o.ToBitString().GetHashCode();
}
}
如果我们将EqualityComparer传递给GroupBy
,我们现在可以很容易地得到我们的计数:
var list = new List<BitArray>
{
new BitArray(new bool[] { true, true } ),
new BitArray(new bool[] { true, false } ),
new BitArray(new bool[] { true, false } ),
new BitArray(new bool[] { false, false } )
};
var groups = list.GroupBy( item => item, new BitArrayComparer() );
foreach (var g in groups)
{
Console.WriteLine("Value '{0}' occurs {1} times", g.Key.ToBitString(), g.Count());
}
输出:
Value '11' occurs 1 times
Value '10' occurs 2 times
Value '00' occurs 1 times