Reputation: 57
I have array of Bitarray (each element consists of 128 bits) and I want to find the duplication of each element of it.
I've tried this code:
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);
}
but I don't want to convert it to string because the results will be false.
I want to know the duplication of each element of array of bitarray.
Can anyone help?
Upvotes: 0
Views: 209
Reputation: 52240
It's pretty easy to convert a BitArray to a string of 1s and 0s:
static public string ToBitString(this BitArray This)
{
return string.Join("", This.Cast<bool>().Select( bit => bit ? 1 : 0 ));
}
With this knowledge, we can write an EqualityComparer for BitArray, like this:
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();
}
}
If we pass the EqualityComparer to GroupBy
we can now get our counts very easily:
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());
}
Output:
Value '11' occurs 1 times
Value '10' occurs 2 times
Value '00' occurs 1 times
Link to example code on DotNetFiddle
Upvotes: 0