Question

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]

Was it helpful?

Solution 3

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!");
    }

OTHER TIPS

I think I would use the following method, which makes the algorithm reusable and support any number of arguments. It returns true only if exactly one argument was true.

private boolean oneTrue(boolean... args){
    boolean found = false;

    for (boolean arg : args) {
        if(found && arg){
            return false;
        }
        found |= arg;
    }
    return found;
}

You can test it like this:

private void test(){

    boolean a = false;
    boolean b = true;
    boolean c = false;
    boolean d = false;

    System.out.println(oneTrue(a,b,c,d));
}

Shortest pure bool solution which I can suggest:

System.out.println((a | b) ^ (c | d)) & ((a ^ b) | (c ^ d));

But in your program already already used 1 and 0, if it variables always 1 and 0, you may not use boolean just use following:

if (a + b + c + d == 1)
{
  // true
} else
{
  // false
}

if this varibales may have any values. In this case I recommend convert it to 1 and 0 instead of boolean and again can simply calculate sum.

You can use the following expression:

a && !(b || c || d) ||
b && !(a || c || d) ||
c && !(a || b || d) ||
d && !(a || b || c)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top