我有兩個bitarrays,每個長度爲200.000。我需要在相同的順序中找到每個列表中有多少個1。讓我畫出來:比較兩個二進制向量
1 0
**1 1**
0 0
0 1
0 0
**1 1**
1 0
0 1
.. ..
所以結果應該是2
和我做的 - 兩個這種比較嵌套換約20萬次:)。
我現在用bitarray與&運算符比使用popCount方法找到結果。
那麼你對這類問題有什麼建議。你會在哪裏儲存這些載體,以及如何以我想要的方式比較它們?我需要速度。
更新: 我已經做了760長度的數組,這與我的方法花了5秒。在評論中提出的每種方法花費了> 1分鐘(我停止了該計劃) 因此,我猜它是我必須回答的。我簡化了我的代碼。
for(i<761)
var vector1 = matris[getvectorthing];
for(j=i+1<761)
{
var vector2 = matris[getvectorthing];
var similarityResult = vector1Temp.And(vector2);
var similarityValuePay = popCount(similarityResult);
//similarityValuePay is result that i want
}
}
private static int popCount(BitArray simRes)
{
Int32[] ints = new Int32[(simRes.Count >> 5) + 1];
simRes.CopyTo(ints, 0);
Int32 count = 0;
// fix for not truncated bits in last integer that may have been set to true with SetAll()
ints[ints.Length - 1] &= ~(-1 << (simRes.Count % 32));
var tempInt = ints.Where(k => k != 0).ToArray();
for (Int32 i = 0; i < tempInt.Length; i++)
{
Int32 c = tempInt[i];
// magic (http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel)
unchecked
{
c = c - ((c >> 1) & 0x55555555);
c = (c & 0x33333333) + ((c >> 2) & 0x33333333);
c = ((c + (c >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
}
count += c;
}
return count;
}
我問了一下,因爲可能有很多切肉刀方法或簡單的調整來提高性能。例如:
var tempInt = ints.Where(k => k != 0).ToArray();
這個ToArray()似乎是我需要修復的一部分。等
寫一些代碼並告訴我們。 – nicomp
*「-two nested for-」* - 您爲什麼需要它? –