Intelligent code made easy

April 24, 2007

I find the topics of Artificial Intelligence and Machine Learning extremely intriguing. In fact, one of the reasons I decided to study Computer Science was my perception of these concepts. I viewed them as extremely complex and equally difficult to implement.

Well, this isn’t always the case. In fact, I’ll show you an easy way to add some AI to your applications using an example. Let’s look at a snipet of code from my rubyquiz submission this week. Now, please, don’t think that I have delusions of grandeur and believe this to be an actual example of true AI, but think of this as barely scratching the surface to simply introduce how to think about adding some type of intelligent behavior to your application.

Anyway, this week’s quiz focused on getting a bit of Morse code from the user and then presenting all the possible translations of the code. I decided to add a nifty little feature that would make a “best guess” at which of the many possible translations was the true intent of the sender. How did I do it? Simply put: word frequency.

Sounds scary, but it’s not. My program read through a text document of a Sherlock Holmes novel, counted the number of times each word appeared and then stored these word -> frequency pairs in a hash. Then, when presenting my possible translations to the user, I simply showed the words with the highest occurrence in the Holmes novel first.

This clever (and simple, I don’t flatter myself) trick gives my program a bit of intelligence. In fact, this is a very simple example of a Bayesian filter (check wikipedia for more info). I’ll post the “intelligent” code snipet below. And just think; if I can do something like this, so can you. And probably something way cooler.

My code


Leave a Reply

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

You are commenting using your 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

%d bloggers like this: