# The Portfolio Website of Aaron Cook

## Using Karnaugh Maps to Simplify Code

When writing code, Boolean logic is used in just about everything. Sometimes, Boolean conditions, like If Statements, can get overly complicated. This is especially troublesome when working with someone else’s code. Using Karnaugh Maps is a great way to simplify and debug these statements.
Karnaugh maps are essentially another form of a truth table. They are especially helpful when simplifying large Boolean expressions, but in this example I’ll keep things simple. Suppose there is an expression in your code that you want to simplify, shown below.

```if(functionA() = true AND functionB()=true){
Print=”Success”;
}else if(functionA() = true AND functionB()=false){
Print “Success”;
}
```

The first step is to convert this code into Boolean algebra. Let functionA() be denoted as A and functionB() as B.

At this point, it should be obvious how to simplify this expression using other methods. But we’re interested in Karnaugh Maps. The first step in setting up the Karnaugh Map is setting up the table. Create a table, as shown. Each cell of the table represents the result of a product pair. For example, the first cell in the table is AB.

Now, place the results of the product pairs in the table for our expression AB + AB’. From this expression we know that AB is true and AB’ is true. Denote true as 1 and false as 0.

Take note of adjacent cells that are true and circle them.

Next we gather all the circled variables and write them down

Remove duplicates from the list: we have two As, we simply combine them as one variable. We also must remove opposites. B and B’ (“B and not B”) are opposites. Remove them from the list as well. This leaves us with A, which cannot be reduced any further and is the simplified version of AB + AB’.

Now that we have our simplified expression, we can convert it back into code. Our new cleaned up code becomes:

```If (functionA() = true){
Print (“Success”);
}
```

This was an extremely simple example of how Karnaugh Maps can be used to simplify code. They’re even more useful when dealing with more complex Boolean expressions. For further reading, I suggest the following:

On March - 1 - 2010

### 2 Responses to “Using Karnaugh Maps to Simplify Code”

1. Alex says:

Some of helps for this idea implremented in Gorgeous Karnaugh software – look to the article on program’s site here:
http://gorgeous-karnaugh.com/home/gorgeous-karnaugh-for-programmers/

• Aaron says:

Awesome idea! Karnaugh maps are far too underused in the software engineering field. Perhaps tools like yours will make them more accessible.