Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorter way to check multiple or conditions

Is there any easier way of checking one variables value against several others? Currently I'm using code like this:

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 I can use a switch, but then I'd have to write my function several times. Is there an easier way of doing this?

like image 246
Some Guy Avatar asked Oct 28 '11 15:10

Some Guy


3 Answers

You do not need to write your function several times with a 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.
}

Amusingly, however, this is just about the same number of characters (depending on how you format it). A switch statement in general is less powerful than an explicit if statement, but in this case I find it clearer and less error-prone.

like image 79
Phrogz Avatar answered Sep 18 '22 16:09

Phrogz


And better yet:

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

Move the logic out of the mainline code into an appropriately-named method.

This also lets you do your bounds checking there (if it isn't already guaranteed elsewhere).

like image 35
Dave Newton Avatar answered Sep 21 '22 16:09

Dave Newton


No. However the following looks neater:

if(a[i] == a[i-13] || 
   a[i] == a[i+13] || 
   a[i] == a[i-1] || 
   a[i] == a[i+1]
) {
  //my code
}
like image 36
Raynos Avatar answered Sep 20 '22 16:09

Raynos