Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if int[] contains only certain numbers?

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");
like image 747
LeftRight92 Avatar asked Nov 18 '15 18:11

LeftRight92


1 Answers

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't 0 or 1 in it. Another solution might be to use a bool[] 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 an enum, 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). Use Any instead (but it's still doing basically what your for loop is doing - best case O(1), worse O(n) average O(n)).

if (myArray.Any(a => a != 0 && a != 1))
{
     // ....
}
like image 130
Matt Burland Avatar answered Sep 27 '22 21:09

Matt Burland