May 18, 2011

C++ Function Templates

One of the seldom used features of the C++ programming language is type parametrization a.k.a. Template. This often overlooked feature actually enables a separate programming paradigm - Generic Programming. This allows functions and classes to operate on generic data types. Functions and classes can work on many different data types without being rewritten for each type. There are two kind of templates in C++, function templates and class templates.

Templates provide a way to reuse source code. Here they differ from inheritance and composition which provide ways to reuse object code. This also implies that using templates will cost more time in compilation. However, unless the template is a very complex one, the additional time in compiling is negligible.

A function template for finding maximum of two instances of the same type can be coded as following :

template <typename T>
T& max(T& x, T& y)
if(y < x)
return x;

return y;

This template function can be used for native data types as well as classes provided that the "<" operator has been overloaded for that class. The compiler will replace the T in template code with appropriate types during compilation.

If a template function is required to behave in a certain way for a certain data type, it can be specialized for those data types.

One important point about template functions is that, when working in multiple-file projects, the declaration and definition has to be in the same file.

May 16, 2011

Visualizing Genetic Algorithms 1

I've started working on a Genetic Algorithm visualizer tool. The primary goal is to visualize every individual (suboptimal solution) in every generation till termination of the algorithm. Each individual is assigned an unique ID which, along with the individual's parents' IDs can be seen on top left corner of each icon. The number at the bottom left corner is the fitness value of the individual. Apart from this, average fitness, best fitness of every generation are also plotted. Using C++ and OpenGL to build the visualizer tool.

In the picture above, I'm trying to breed a regular pentagon starting with initial population of 20 randomly generated pentagons. The fitness function used here is the standard deviation of distances of the vertices from a point inside the pentagon. Here we can see the 11 generation of pentagons on the same page. I will be posting more updates.