I’ve been studying artificial intelligence for many years. One of the AI constructs that has fascinated me the most has been Genetic Algorithms (GA). With a GA, one “evolves” a solution to ones problem. A “gene” is a candidate solution to a problem, and individual alleles in that gene are individual parameters to the function that attempts to solve the problem. The output of the function is evaluated for “fitness”–essentially, how well it solved the problem–and good candidates are intermingled for the benefit of future generations, while particularly bad candidates are discarded; “survival of the fittest” in its most incredibly literal sense.
This little sketch was written for a couple of reasons. First, I’ve been seeing some AI code that I felt like has been overly complicated. A lot of principle AI algorithms are quite simple to implement, once you understand them. But also, I wanted to demonstrate the flow of a GA and how it tends to find intermediate solutions, improving over time.
This sketch will require some basic programming knowledge to be able to alter the fitness function and make the GA do different things, but I think it can be an exciting and compelling exploration into code. There are actually a few simple things one can do to alter the course of the algorithm. Each “gene” represents a row of pixels in the image being drawn when you click “start”. As it currently stands, it will “evolve” solutions converging on the color red. If you change “if((i%4)===0)”* to read “if((i%4)===1)”, it will converge on green. “if((i%4)===2)” converges on blue. There is a 4th opacity component at #3, but it basically just ends up showing black. It isn’t necessary but I just didn’t feel like fixing the code to get rid of it, and maybe someone else will find it useful.
Instead of “if((i%4)” you replace the 4 with another number–say a prime number like 31–you get some interesting results as well. There are a lot of things that you could do here, it’s just a matter of whether or not you wish to pluck at it.
* the percent sign, ‘%’, is known as the modulus operator. For positive numbers, it returns the remainder of a division operation. So, “13 % 5 ” return 3 because 13 divided by 5 is 2 remainder 3 (i.e. 2 x 5 + 3 = 13).
Offtopic: Stick Together. Get it?