Let's say I have a boolean array with:
{false, true, false, false, true, true, ...}
What is the quickest way (most optimized) to get the indices of the (for instance) false elements? In this case 0 2 3
?
A for loop is likely the fastest way to do this:
List<int> indices = new List<int>();
for (int i=0;i < theArray.Length; ++i)
{
if (theArray[i])
{
indices.Add(i);
}
}
Note that you can probably gain a slight bit of speed at the cost of extra memory by preallocating the List<int>
:
List<int> indices = new List<int>(theArray.Length);
This will avoid extra memory allocations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With