Saturday, May 14, 2016

Better algorithms (2)

This is one more article in a series showing how to achieve better programs just by not believing your algorithms are good enough and refactoring them until perfection. Or at least until someone appear with a better algorithm. The first article, for those who haven't seen it, is here.

This time I'm going to talk about another simple problem, counting the most frequent character in a string. This question I gave to my students, generated this code here:

A simple exam of this code shows that we are taking a lot of lines (from 4 to 8) just for initializing the hash of the counts. We can save some code with just a few changes:

Now we are a few lines shorter and much more readable. The inline if helps a lot in readability, because sentences are much more natural with it. Think about it and you'll see that "Do something if this happens" is more natural than "if something happens do something, else do something else".

Making code better in Ruby, of course, is a matter of knowing the core libraries. All this code above is for students. A real code for professionals would be much more like:

As you may see, all that code may be simplified to only three lines. This was possible because we reminded the fact that the Hash has an option for creation that allows you to specify a default value for newly created items. In this case this value was set to zero.

The use of max_by, a method descending from Enumerable class, which is an ancestor of Array, make possible for us to remove all lines from 7 to 15, which is a lot of code.