A shorter way to check for multiple or conditions

Is there an easier way to check one variable value against several others? I am currently using the following code:

if(a[i] == a[i-13] || a[i] == a[i+13] || a[i] == a[i-1] || a[i] == a[i+1]){ //my code } 

Now, is there a shorter way to do this? I know that I can use switch , but then I would have to write my function several times. Is there an easier way to do this?

+6
source share
3 answers

You do not need to write your function several times with the switch:

 switch(a[i]){ case a[i-13]: case a[i+13]: case a[i-1]: case a[i+1]: // This code will run if any of the above cases are true. } 

Interestingly, these are about the same number of characters (depending on how you format it). The switch statement is generally less efficient than the explicit if , but in this case I find it more clear and less error prone.

+5
source

And even better:

 if (matchesAdjacent(a, i)) { // etc. } 

Move the logic from the main line code to the method with the corresponding name.

It also allows you to check your boundaries (if it is not guaranteed elsewhere).

+2
source

Not. However, the following looks more neat:

 if(a[i] == a[i-13] || a[i] == a[i+13] || a[i] == a[i-1] || a[i] == a[i+1] ) { //my code } 
+1
source

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


All Articles