javaalgorithmif-statementlogicpseudocode

How do I convert if else to && || in if the result is the same


how do i replace if else to && || if the output for each condition is the same in these cases

there are multiple different conditions to be met before reaching the outputs and each case has the same output.

Note that the conditions and outputs are just placeholders since this is mostly a pseudo code question

Case 1:

if(condition 1){
    if(condition 2){
        if(condition 3){
            if(condition 4){
                if(condition 5){
                    return(1);
                }
                if(condition 6){
                    if(condition 7){
                        return(1);
                    } 
                }
            }else{
                if(condition 10){
                     return(1);
                }
            }
        }
    }
}

Case 2:

if(condition 1){
    if(condition 2){
        if(condition 3){
            if(condition 4){
                if(condition 6){
                    if(condition 8){
                         return(2);
                        }   
                }else{
                    if(condition 9){
                        return(2);
                    }
                }
            }
        }else{
            if(condition 11){
                  return(2);
            }
        }
    }else{
        if(condition 12){
            return(2);
        }
    }
}else if(condition 13){
    if(condition 14){
        return(2);
    }
}

can it be possible to reduce both the cases to 1 if statement each by using && and || operators with the conditions since both return a single result despite having multiple conditions

the solution I am looking for would look something like: Case 1:

if((condition1 && condition 2) || (condition 3)){
   return (1);
}

Case 2:

if((condition1 && condition 2) || (condition 4)){
   return (2);
}

Solution

  • If in case all the conditions have the same result, then you can condition it like this:

    case1:

    if ( (condition1 && condition2 && condition3) && ((condition4 && condition5) || (condition4 && condition6 && condition7) || (condition10)) ) return(1);
    

    case2:

    if ( (condition1 && ((condition2 && ((condition3 && condition4 && ((condition6 && condition8) || condition9)) || condition11)) || condition12)) || (condition13 && condition14)) return(2);