Optimal “if-else” tree algorithm to minimize duplicate code

algorithmsgraphtrees

I'm having trouble formulating this problem as an algorithm:

I have a set of conditionals (combined with &&) and operations, for example:

if (A && B)
    execute C
else if (D && A)
    execute E

I want an algorithm to find the optimal "if-else" tree that minimizes the amount of duplicate code. The optimal branching for the example above would be:

if (A){
    if (B)
        execute C
    else if (D)
        execute E
}

The cost of duplicate conditionals will be different for each conditional, but it is at least 1. The cost for duplicate operations (e.g. execute C) is 3.

This smells like a minimum spanning tree problem, to me. Or maybe some other known graph theory problem. But I can't figure out how to represent the problem as a graph to begin with.

Here is a comparison of the two "if-else" trees from the example:

example graph

Best Answer

Avoid nesting logic into inner blocks as much as possible. It makes code harder to read.

if (!A)
   return

if (B)
   execute C

if (D)
   execute E

Exit if not A. Otherwise B or D, but if you know D is already true when B is false. You could drop the if (D) and just execute E.

In cases like this it's preferred to use a switch.

if (!A)
   return

switch R
    case B:
       execute C
       break
    case D:
       execute E
       breal
Related Topic