How to check if int [] contains only certain numbers?

I need to check that int [] contains only certain values ​​(in this case 0s and 1s) and throws an exception if this is not the case.

Is there a more efficient way to do this than any 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"); 
+5
source share
3 answers

You cannot check an array without iterating through it. So O(n) is the best you get. Another solution would be to control the loading of the array and throw an exception when someone tries to put a value in it that is not 0 or 1 . Another solution might be to use bool[] , which has only two possible values ​​anyway, but will require some conversion if you really need numbers. (Note: if you need more than two values, it might make sense to take a look at enum , especially if those values ​​should represent something)

In addition, Where not the best solution here, because you are forced to check the entire array (without early exit). Instead, use Any (but it still does basically what your for loop does - the best case is O(1) , worse than O(n) average O(n) ).

 if (myArray.Any(a => a != 0 && a != 1)) { // .... } 
+12
source

You can try using Array.TrueForAll :

 if (!Array.TrueForAll(myArray, n => n == 0 || n == 1)) throw new Exception("Array contains invalid values"); 
0
source

Here is a blog post according to your question http://www.tkachenko.com/blog/archives/000682.html

checked for

 int[] data = new int[100000000]; 

If you are really interested in performance, you should not use Any () for sure)))))

since you need to look for a pair of values ​​in an array, the answer is - to search for a loop or foreach (in your case int [] compiled in CIL, as for a loop) - the best options for you

 foreach loop search: 39 ms for loop search: 39 ms Contains() method search: 56 ms Any() method search: 446 ms IndexOf() method search: 57 ms 
0
source

Source: https://habr.com/ru/post/1236258/


All Articles