I need to check that an int[] contains only certain values (in this case 0s & 1s) and throw an exception if it doesn't.
Is there a more efficient way to do it than either of the following solutions?
Simple (but O(n)):
for(int n = 0; n < myArray.Length; n++)
if(!(myArray[n] == 0 || myArray[n] == 1))
throw new Exception("Array contains invalid values");
Using Where():
if(myArray.Where(n => !(n==1 || n==0)).ToArray().Length > 0)
throw new Exception("Array contains invalid values");
You can't check an array without iterating through it. So
O(n)
is the best you are going to get. The other solution would be to control loading the array and throw an exception when somebody tries to put a value that isn't0
or1
in it. Another solution might be to use abool[]
which only has two possible values anyway, but would require some conversion if you actually need numbers. (Note: if you needed more than two values, it might make sense to look at anenum
, especially if those values are supposed to represent something)Also,
Where
is not the best solution here because you are forced to check the whole array (no early exit). UseAny
instead (but it's still doing basically what your for loop is doing - best caseO(1)
, worseO(n)
averageO(n)
).You can try to use
Array.TrueForAll
:Here is research blog post according to your question http://www.tkachenko.com/blog/archives/000682.html
tested on
if you are really interested in performance you shouldn't use Any() for sure )))))
so as far you need to search for couple values in array the unswer is - for loop search or foreach (in your case of int[] compiled into the CIL as for loop) is the best options for you