Dirty Code

It’s official: I just wrote the ugliest method I’ve ever written.

While working on a branch-and-bound algorithm for a Capacitated Facility Location Problem, I got frustrated with the low efficiency of my program. However, I was pretty sure that my choice of bounds was optimal. I figured the problem might be caused by a bad subproblem order. So I decided to try something new and sort customers by descending required size.

There must be an easy way to sort keys by their values in Java, right? Well, maybe there is, but I couldn’t find it. Obviously, I could use a lambda expression, but I’m not allowed to do so in this class. My quick google search led to lots of related Stackoverflow questions where people were told to write a quick method themselves. However, I was tired and frustrated and didn’t want to spend 20-30 minutes on that problem. The code wasn’t even meant for the final version of my algorithm, I just wanted to debug!

So I hacked it.

TreeMap<Double, Integer> tree = new TreeMap<>(Collections.reverseOrder());
for (int i = 0; i < customerNumber; i++) {
    tree.put(requirement(i) + Math.random(), i);
}
List<Integer> orderedCustomers = new ArrayList<>(tree.values());

Turns out this fixes my problem. I feel so dirty now.

Hopefully I’ll find enough time to replace this abomination tonight. I’ll keep you updated.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s