Search code examples
javaalgorithmif-statementboolean-operations

Convert four combination of Boolean into true/false - With IF Else statement


I actually try to convert four different Boolean into true/false.

My case is,

   True false false false Then true else false
   false True false false Then true else false
   false false True false Then true else false
   false false false True Then true else false

I tried like this,

int a=1;
int b=0;
int c=0;
int d=0;

int cnt=0;

// A block of code will be executed only when any one of the four variables is 1 and
//the rest of them is 0. and another block will be executed when the above mentioned
//condition become false.

if (a==0) { cnt+=1; }
if (b==0) { cnt+=1; }
if (c==0) { cnt+=1; }
if (d==0) { cnt+=1; }

if (cnt==3) { // true block } else { //false block } 

The above code is working perfectly fine, But i had taken a challenge to check this condition in a single if statement. Then i tried like this.

if(!((!(a==0) && !(b==0)) &&  (!(c==0) && !(d==0))))
{
   //true block
}
else
{
   //false block
}

The above condition is failing in some combinations(a=1 b=0 c=1 d=1). Can anybody point out what the issue is.? or suggest any new ideas.?

My objective is convert (3 false + 1 true) into true other wise into false.

[Note: I just gave the scenario for understanding purpose only. a,b,c,d value may be differ. See my objective. Don't say answers in favor of 1 and 0]


Solution

  • How about this?

        boolean a = true;
        boolean b = false;
        boolean c = false;
        boolean d = false;
    
        if ((a ? 1 : 0) + (b ? 1 : 0) + (c ? 1 : 0) + (d ? 1 : 0) == 1) {
            System.out.println("You win!");
        }
    

    [edit]... or here's another way to do it :

        if ((a ^ b ^ c ^ d) & ((a & b) == (c & d))) {
            System.out.println("**XOR** You win!");
        }