Reputation: 4492
I currently have a rather large conditional:
a[i1][i2 + 1] == '1' || a[i1][i2 - 1] == '1' || a[i1 + 1][i2] == '1' || a[i1 - 1][i2] == '1'
This works great however I just realised this is only half of what I need. Basically I need at least two of those conditionals to be true
. Is there an easy way to accomplish this or do I have to rewrite the whole thing as needed?
An easy way to showcase what I mean is by the following.
Say I have three conditionals: a, b, and c. What I need in short is (a&&b) || (a&&c) || (b&&c)
Upvotes: 1
Views: 98
Reputation: 7496
Another method is to utilize an Array to store the matched conditions. This way you can still define what evaluates to true
and use the Array to store which conditions matched and view it afterwards.
var matched = [];
if (a[i1][i2 + 1] == '1') matched.push({x: i1, y: i2 + 1});
if (a[i1][i2 - 1] == '1') matched.push({x: i1, y: i2 - 1});
if (a[i1 + 1][i2] == '1') matched.push({x: i1 + 1, y: i2});
if (a[i1 - 1][i2] == '1') matched.push({x: i1 - 1, y: i2});
if (matched.length >= 2) {
console.log('These matched!', matched);
}
Upvotes: 1
Reputation: 6123
Since true+true+false === 2, you can simply say:
((a[i1][i2 + 1] == '1') +
(a[i1][i2 - 1] == '1') +
(a[i1 + 1][i2] == '1') +
(a[i1 - 1][i2] == '1'_) >= 2
Upvotes: 1
Reputation: 2136
You can try something like this.
var numberOfTrue=Number(a[i1][i2 + 1] == '1')+ Number(a[i1][i2 - 1] == '1'); // +....
if(numberOfTrue>=2){
//TODO
}
http://jsbin.com/wasuwoxe/1/edit
Upvotes: 2
Reputation: 3837
what about something like this?
var o = i1 + 1;
var p = i1 - 1;
var q = i2 + 1;
var r = i2 -1;
a[i1][q] == '1' || a[i1][r] == '1' || a[o][i2] == '1' || a[p][i2] == '1'
or something like this:
var a; // you should init this array in somewhere else above
function isValid(i1, i2){
return (a[i1][i2 + 1] == '1' || a[i1][i2 - 1] == '1' || a[i1 + 1][i2] == '1' || a[i1 - 1][i2] == '1')
}
Upvotes: 0