Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the fastest way to get all of the indices of false elements in a boolean array?

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?

like image 765
David West Avatar asked Nov 30 '22 12:11

David West


1 Answers

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.

like image 75
Reed Copsey Avatar answered Dec 04 '22 00:12

Reed Copsey