views:

77

answers:

3

Following parameters are given:

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

I want to have minimal code of this version:

if ( ( a && ! b) || ( ! a && b) ) {
    z1 += 99 ;
}

if (a ^ b) {
    z1 += 19 ;
}

if ( ( a && b) || ( ! a && ! b) ) {
    z1 += 118;
}

What needs to be modified?

+2  A: 
if ( ( a && ! b) || ( ! a && b) ) {
}  

you can use

if ( a!=b) {
} 

if ( ( a && b) || ( ! a && ! b) ) {}  

you can use

if(a==b){}  

if (a ^ b) {}   

is ok in its place

org.life.java
+8  A: 

The first condition is the same as the second, the third is the negation of the others, so we have

if (a ^ b) {
   z1 += 99 + 19  // = 118
} else {
   z1 += 118
}

We can shorten that again, whatever a or b is, z1 is augmented by 118, so we just have

z1 += 118
Julien
Gosh ! Didn't saw that one coming !
Riduidel
the code should do the same with any a,b,c given, so the first and the second condition would not be the same?
ArtWorkAD
Make a truth table if you don't believe me, the two conditions are the same whatever a or b are...
Julien
thanks, I acutally did that and it works
ArtWorkAD
+2  A: 

If you need to figure out things like this in future then you might want to try writing a table (I think its called a truth table, but some of the more mathematically minded here may correct me) showing all possible inputs and their respective outcomes. Once you've written the table you should be able to quickly identify the overall logic and possibly simplify it.

For the above a table might look like this;

  a  |  b  |  z1
------------------
  t  |  t  |
  t  |  f  |
  f  |  t  |
  f  |  f  |

Go through each row and write the effects of z1 in the column. This should allow you to easily determine what's going on and how to shorten it, if possible.

Qwerky