A better algorithm to generate random names

In October I published a post about an Algorithm to generate random names. If you came here looking for a way to generate random names, I suggest you go read that post, skim over the source code and then later come back here for the much better version.

The program worked in two parts, a script to generate probability tables and a class called RandomNameGenerator. The script was quickly thrown together. I wanted to save time since this was a small part of a larger project.

When it came time, months later, to add more features and correct some bugs I quickly regretted my decision to “quickly throw together” a script to generate the probability tables. The whole thing was hard to understand and extend. The version I was working with was more involved than what I had originally posted, and using a simple script wasn’t cutting it any more. I had fallen into the proverbial “working fast but taking much more time in the end” trap.

So I started the whole thing over using test-first BDD, OO principles and applying care to my work. In not much more time than it took me to write the first version I had a working second version with the features I wanted and I got rid of the bugs that were bugging (pun intended) me.

I put the whole thing on GitHub so you can go there for the source code and to get a working copy.

I have included some sample data to use to generate names. It’s under the /media directory and it uses names from Greek mythology (all taken from Wikipedia).

There is a small program called fix_sample.rb that will try to convert a sample file to the desired format. The sample is expected to be in following format:

firstName secondName thirdName

Which is a space-delimited plain text file that starts and ends with a space.

The tests are found in the /spec directory.

A sample program, random_name_generator_test.rb provides a sample usage of the program for those who want to know how to call it.

Since this test program is very small I’ll reproduce it here in it’s entirety:

require_relative 'random_name_generator'

generator = RandomNameGenerator.new("media/greek_myth_sample")

puts "Generating 40 names"
40.times {puts generator.generate}

This test program will generate 40 random names and output them to the console, that’s all there is to it.

Here is a sample output:

Ados
Heria
Zeusa
Lestia
Caemis
Catosesos
Hersa
Amede
Meliasa
Kraera
Celespa
Anyssa
Demine
Agra
Uros
Dikia
Arcos
Hemesiste

Take care.

One thought on “A better algorithm to generate random names

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