r/dailyprogrammer • u/jnazario 2 0 • Jan 13 '16
[2016-01-13] Challenge #249 [Intermediate] Hello World Genetic or Evolutionary Algorithm
Description
Use either an Evolutionary or Genetic Algorithm to evolve a solution to the fitness functions provided!
Input description
The input string should be the target string you want to evolve the initial random solution into.
The target string (and therefore input) will be
'Hello, world!'
However, you want your program to initialize the process by randomly generating a string of the same length as the input. The only thing you want to use the input for is to determine the fitness of your function, so you don't want to just cheat by printing out the input string!
Output description
The ideal output of the program will be the evolutions of the population until the program reaches 'Hello, world!' (if your algorithm works correctly). You want your algorithm to be able to turn the random string from the initial generation to the output phrase as quickly as possible!
Gen: 1 | Fitness: 219 | JAmYv'&L_Cov1
Gen: 2 | Fitness: 150 | Vlrrd:VnuBc
Gen: 4 | Fitness: 130 | JPmbj6ljThT
Gen: 5 | Fitness: 105 | :^mYv'&oj\jb(
Gen: 6 | Fitness: 100 | Ilrrf,(sluBc
Gen: 7 | Fitness: 68 | Iilsj6lrsgd
Gen: 9 | Fitness: 52 | Iildq-(slusc
Gen: 10 | Fitness: 41 | Iildq-(vnuob
Gen: 11 | Fitness: 38 | Iilmh'&wmsjb
Gen: 12 | Fitness: 33 | Iilmh'&wmunb!
Gen: 13 | Fitness: 27 | Iildq-wmsjd#
Gen: 14 | Fitness: 25 | Ihnlr,(wnunb!
Gen: 15 | Fitness: 22 | Iilmj-wnsjb!
Gen: 16 | Fitness: 21 | Iillq-&wmsjd#
Gen: 17 | Fitness: 16 | Iillq,wmsjd!
Gen: 19 | Fitness: 14 | Igllq,wmsjd!
Gen: 20 | Fitness: 12 | Igllq,wmsjd!
Gen: 22 | Fitness: 11 | Igllq,wnsld#
Gen: 23 | Fitness: 10 | Igllq,wmsld!
Gen: 24 | Fitness: 8 | Igllq,wnsld!
Gen: 27 | Fitness: 7 | Igllq,!wosld!
Gen: 30 | Fitness: 6 | Igllo,!wnsld!
Gen: 32 | Fitness: 5 | Hglln,!wosld!
Gen: 34 | Fitness: 4 | Igllo,world!
Gen: 36 | Fitness: 3 | Hgllo,world!
Gen: 37 | Fitness: 2 | Iello,!world!
Gen: 40 | Fitness: 1 | Hello,!world!
Gen: 77 | Fitness: 0 | Hello, world!
Elapsed time is 0.069605 seconds.
Notes/Hints
One of the hardest parts of making an evolutionary or genetic algorithm is deciding what a decent fitness function is, or the way we go about evaluating how good each individual (or potential solution) really is.
One possible fitness function is The Hamming Distance
Bonus
As a bonus make your algorithm able to accept any input string and still evaluate the function efficiently (the longer the string you input the lower your mutation rate you'll have to use, so consider using scaling mutation rates, but don't cheat and scale the rate of mutation with fitness instead scale it to size of the input string!)
Credit
This challenge was suggested by /u/pantsforbirds. Have a good challenge idea? Consider submitting it to /r/dailyprogrammer_ideas.
4
u/jnazario 2 0 Jan 13 '16 edited Jan 13 '16
playing around in scala:
at each generation it creates a new batch of 100 samples mutated with the specified
rate, which simply determines if the character should be replaced with a new random character. it then finds the best match as determined using the hamming distance (number of different characters, a very simple string distance method) to repeat the process, using that best fit as the seed for the next generation. this lets it get iteratively closer to the target string.what's neat about this is that a too high rate and you get unstable strings - you get a position match that then mutates away, and you never converge. too low and it takes too long. there's definitely a knife edge here. i made a simple scatter plot showing the mutation rate for the string "Hello, world!" vs the convergence time in rounds. https://docs.google.com/spreadsheets/d/15mvLPvX7GsxP1bn1NZU6unEtOHH-J5kdkb6I03I8Sl0/pubchart?oid=853233453&format=image
11
u/[deleted] Jan 13 '16
Hah, I made this thing before, except it evolved "I think therefore I am", jokingly trying to make the point that
to thinkis maybe a bad metaphor in CS. It should work for this challenge with a few small modifications, maybe I'll post it later.6
u/[deleted] Jan 13 '16 edited Jan 13 '16
Hey its my challenge! If anyone needs help i'd be happy to give advice.
Here are some solutions i made:
This one is an evolutionary algorithm i made for another challenge. Each iteration it changes one character randomly in each member of the population and it replaces one member of the population with a set of totally random new characters. Link to Evolutionary Algorithm
This one is a genetic algorithm. It's vectorized so the only loop in the program is the generation increment and everything else is handled by matrix operations built into Matlab. Link to Genetic Algorithm
edit: ah i forgot to mention the genetic algorithm has an different examples of selection and crossover types so you can see how they change the rate of convergence. I seem to have best luck with tournament selection and 1-point crossover crossover.
edit2: this should allows you to run the genetic algorithm in an online IDE. It seems to work on my computer so i assume the link will work for others?
5
u/carrutstick Jan 14 '16 edited Jan 14 '16
Got home from work and realized no-one had made a Haskell version, so here's my quick attempt. (Really I just wanted to play with the
Randommonad).4
u/stage_hazard Jan 13 '16 edited Jan 14 '16
I forced myself not to look at the notes from my AI class, so I hope this is actually a genetic algorithm.
Python 3:
3
u/casualfrog Jan 13 '16
JavaScript
Pretty dumb fitness function. Inspired by /u/jnazario's code.
Example output:
3
u/lucaswerkmeister Jan 13 '16
Ceylon: gist, try online.
ceylon.numericmodule, which adds cross-platform random numbers (among other numeric things), but isn’t in the 1.2.0 distribution. The “try online” version directly uses JSMath.random()instead.Sample output:
3
u/mc_kay Jan 13 '16 edited Jan 13 '16
Python 3, second attempt, population starts at 5 and is capped at 100 and the top 20 parents by Hamming distance contribute to next generation. Each parent gives half of their string to their child and then the child has a 50% chance of a one character mutation. Returns the generation when one child is the input value. Fun to make but it's slow, feedback appreciated
Average output generation after 100 iterations
3
u/FlammableMarshmallow Jan 13 '16
Python3
I spent around a few hours trying to solve this in Haskell, but sadly I could not do it.
I decided to do it in Python, and did it in around 10 minute, but I still will try to solve it in Haskell and I'll post it if I get it done before tomorrow.
Advice both for the Python version and the Haskell version is appreciated (and needed :p)
3
u/auradog Jan 15 '16
c++ This is my second time using this language, and my first time submitting to this sub, so I'd definitely appreciate comments/criticism. I'm not completely sure if what I did is correct - it works for any input string, but it takes quite a few generations to get there. (avg like 4 thousand)
Tell me what you think!
5
u/Godspiral 3 3 Jan 13 '16 edited Jan 13 '16
In J,
2 step approach similar to hamming distance. (mastermind score of black pegs only).
algorithm description might be "generational set reduction" from hamming distance black box.
1st step filters allowed sets for each letter position starting from 91 ascii of
' ' to zHoping for scores of 0, as that allows every position to eliminate that draw from their set. Saves any random draws that had scores > 0 along with their score.just the sets shown. after 172 iterations. About average luck to get it down to 5 in that time. There is 1 in 20 chance to get a 0 score with 5 length sets for 13 positions. Its actually pretty common for 172 iterations to yield final sets of 4.
Next step is to take the saved >0 scores and see if any sets can be proven to be 1. (again common for early saved sets to have just 1 match with sets that were close to 90 long initially, but unlikely to still match a set under 7 long)
Not guaranteed to get 1 letter sets, but likely.
combined steps trying to minimize the initial iteration count:
149 iterations has a >50% chance of finding a unique solution.
159 iterations has a 70% chance of finding a unique solution.
169 iterations had a 10/10 chance of finding a unique solution.
0.00721983 117632 NB. combined steps 169 iterations 7ms
0.00977246 124544 NB. 189 iteration overkill 9ms
version that starts with full ascii sets, 316 iterations (50 + alphabet size has > 90% chance of unique solution). Smaller delta than 91 char alphabet due to more unlikely non-printables being in sets. And easier to guess phrase due to unlikelihood of unprintables and random punctuation.
optimization to short circuit out of 2nd step as soon as all sets already 1,
0.0107401 111360 NB. 10ms for 316 iterations on full ascii permutations.
6
u/[deleted] Jan 13 '16 edited Jan 13 '16
Python 3
2
u/j_random0 Jan 13 '16 edited Jan 13 '16
First try. Not genetic based (that would require a population + cross-over) but successfully generated 'Hello, World!' in some 1300+ generations.
A true genetic solution would converge faster (but involve computing each offspring...) because parents would bring improvements with "good genes" in different parts of genome. Of course a few offspring would get double bad genes but those would get culled. :/
2
u/downiedowndown Jan 13 '16
Swift 2 Any Feedback appreciated. My first kind of genetic algorithm so tips are welcome!
2
u/mazenharake 0 1 Jan 13 '16
Coincidentally I was writing a genetic algorithm for the hard challange #248 NotClick Game! :)
Just uploaded the version just now: https://github.com/mazenharake/dailyprogrammer/blob/master/248/dp.py
It is WIP, but I got bored with it to be honest
2
u/errorseven Jan 13 '16 edited Jan 14 '16
AutoHotkey - Went the Genetic route, first time implementing it. Critique welcome.
Edit: Reading through the wiki on Genetic algo, apparently I used the Elitism Method, by only breeding the fittest of each generation. I also didn't include any mutable method that could lose traits, so once a favorable trait was found it was carried over to the next generation combined with traits from the fittest of the bunch. Others have implemented similar solutions, so I'll stand by it.
Output:
2
u/broken_broken_ Jan 14 '16 edited Jan 14 '16
C++14 solution, implemented an evolutionary algorithm with crossover and mutation (1 point, static rate). Finds the wikipedia lorem ipsum in about 50k generations, 15s.
Does anyone happen to have fine-tuned the parameters such as population size, mutation rate, and replacement percentage in population ( called in my code "children_ratio") ? I am quite interested in knowing how to decrease the overall computation time. Keeping the population size low (< 1000) seems paramount...
2
u/ChazR Jan 14 '16 edited Jan 14 '16
Python. This was hilarious fun. I've implemented it with both sexual and asexual reproduction, and with a load of frobs to tweak. You can modify the number of children per generation, the size of the population each generation and the mutation rate.
Sexual reproduction takes about one third the number of generations as asexual.
2
u/minikomi Jan 14 '16 edited Jan 15 '16
Racket Attempt:
Combines two parents:
otherwise:
Example:
2
u/fvandepitte 0 0 Jan 14 '16
Haskell Feedback is welcome.
First time I do something with Genetic Algorithms
Output
2
u/fredrikaugust Jan 15 '16
Just finished my solution on Common Lisp, still kind of new to it, but it works at least.
Gist: https://gist.github.com/FredrikAugust/e0020d55681784bdbb35
2
u/Stefan2142 Jan 15 '16
This sounds really interesting. Can somebody point me to a good beginner resource for learning genetic algorithms?
2
u/mcglausa Jan 15 '16
Python 3
Continuing my attempts to learn Python. I had a lot of fun with this. I tried to design this so that I could implement different methods of crossing, pruning and testing fitness.
Feedback is very welcome!
2
u/j_random0 Jan 13 '16
I scaled my baking temperature to fitness (thinking of simulated annealing cool-down). The problem statement says that's cheating, oops! >.<
1
u/mc_kay Jan 13 '16 edited Jan 13 '16
Python 3, never done an evolutionary program before, this one uses just the Hamming distance so it's not very efficient
The output is really long, but over 1000 runs the average completion generation was
1
u/TheOneOnTheLeft Jan 13 '16
Python 3.
Not 100% sure if this is a good example of an evolutionary/genetic algorithm. It chooses a random character for each position, then if it matches the target, it keeps it, and if it doesn't then it chooses a new random character for the next generation. It replaces all wrong characters every generation. Fitness displayed is Hamming Distance. All feedback is welcome.
1
u/MuffinsLovesYou 0 1 Jan 13 '16
JS I feel like I'm missing something about this challenge, maybe in the concept of mutation, but I only had 30 mins to throw this together so I'll have to revisit it later :P.
1
u/[deleted] Jan 13 '16 edited Jan 13 '16
c# implementation of the python 3 implementation by /u/szerlok
1
u/fibonacci__ 1 0 Jan 13 '16 edited Jan 13 '16
Python
Output
1
u/ThePopeShitsInHisHat Jan 13 '16
Java
First time posting here and definitely not an expert, so any feedback is welcome!
I think I went for a genetic approach, but I'm new to the topic and all my knowledge about this comes from Wikipedia, so I might be mistaken.
I've included the possibility to choose between asexual reproduction (a copy of the current individual is produced) and sexual reproduction (I've implemented one-point crossover but I might add some more later).
One other thing I want to change is how unfit individuals are killed at every iteration: right now just the best half survives, I want to add a bit of randomness to that to assure a little more variability.
The code is probably overly verbose, so here's a link to my GitHub page, hoping this isn't against the rules.
Here is an example output:
1
u/carbonetc Jan 14 '16
I did something like this a while back for the fun of it. I assume that "disqualifies" it, but I figured I'd post it anyway. It's quite dumb and takes hundreds or thousands of generations.
JavaScript
https://jsfiddle.net/pendensproditor/x9ZLg/
1
u/aitesh Jan 14 '16
Erlang
One of my first functioning programs in erlang, went okay but took way too long.
Results:
I am only printing the generations with a changed top fitness.
Usage: Call run with the desired size of each generation (one number).
1
u/alexherrera22 Jan 14 '16
C# any feedback will be well received
1
u/notsonano Jan 14 '16
C++
I am not quite sure if this is exactly what was asked for, but here ya go.
1
u/MthDc_ Jan 14 '16 edited Jan 14 '16
I kind of cheated by using a library I'm developing for Rust, that allows for genetic algorithms to be written without too much boilerplate.
The overal code is still quite long, but that's partly because Rust can be quite verbose in some situations.
Improvements could be a non-static mutation rate and 2-way crossover. Perhaps some other selector would yield better results as well.
1
u/shelakel Jan 14 '16
Go version based on broken's approach, only breeding the top candidates:
1
u/Gobbedyret 1 0 Jan 14 '16
Solution in Python 3.
This challenge has no clear goals to which to optimize the code. Should it run fast? Produce the string in fewest generations? Simulate the genetics of biological organisms?
I'm a molecular biologist by trade, so I was tempted to make a simulation of natural evolution including crossovers, deletions, insertions and genetic drift, but that project was too overwhelming. Instead, I made this simple genetic algorithm that reaches the goal in a few generations.
It typically reaches "Hello, World!" after around 15 generations.
1
u/fbgm1337 Jan 14 '16
JAVA
Output
Code - This is my first genetic algorithm so please critique.
1
u/_morvita 0 1 Jan 14 '16
Solution in Python 3, using Hamming Distance as the fitness function and a uniform-ish crossover. Reaches the target "Hello, world!" string in about 5-6 generations.
1
u/ih8uh8me Jan 15 '16 edited Jan 15 '16
JAVA
This is my first attempt on genetic algorithm and intermediate level challenge! Please leave me any feedback!!
To grasp the idea of GA, I read through /u/timatlee 's code, and was inspired by it!
1
u/Vignarg Jan 15 '16 edited Jan 15 '16
C# I'm 90% sure I did this wrong. Assuming I didn't, easy improvements would be to start with the most common English letters (etnorias), and most of all to feed all the letters to their own instance to be worked simultaneously.
1
u/mips32 Jan 15 '16
Java
Been a while since I've used Java so any feedback is appreciated.
1
u/____OOOO____ Jan 15 '16
Python
Working solution with mutation rate set at 1 and birth rate at 100. Takes 20-70 generations and 0.03 to .11 seconds with these constants. I'm gonna play around with how to accommodate larger strings with different mutation and birth rates.
1
u/error1954 Jan 15 '16
Clojure
This is my first program in clojure, so it's probably pretty bad stylistically and idiomatically, but I'm still proud that I got it working at all.
Here is some sample output:
1
u/CleverError Jan 17 '16
Swift
This is first genetic algorithm I've made and it's pretty cool to see it working, even though I don't know how right it is :P
1
u/Marzhall Jan 17 '16
Here's my solution!
Pretty simple: generate a random seed string the same length as the target string, then create generations based on that random string and choose the best one to make the new seed string. Rinse and repeat!
Here's sample output:
I made an initial mistake in forgetting to seed my 'letters' array with the capital letters, meaning I sat there a little too long with my brows furrowed, trying to figure out why it couldn't get the 'H'.
1
u/[deleted] Jan 17 '16
C# Attempt. Please can I have some feedback, never really touched this subject area but enjoyed the challenge and would be keen to understand if this is a valid algorithm and any improvements.
1
u/nonsane_matty Jan 18 '16
Here's my a link to my submission written in C# (without using LINQ). I haven't implemented to bonus; I feel like going to bed.
https://github.com/nonsane/GeneticSolver/
1
u/Eggbert345 Jan 19 '16
Late to the party, but created one in Golang. My next goal: Create a genetic algorithm to find the optimal parameters for solving this genetic algorithm.
1
u/agambrahma Jan 29 '16
I wrote something in Clojure and it appears to work (though it troubles me that I can't really test this other than looking at it converge).
Runs as follows:
1
u/lnkarma Feb 03 '16
JAVA
With BONUS, you can change the string, population size, mutation rate.
Used genetic algorithm, Hamming distance (fitness function), And Roulette select (selection operator)
SOLUTION
1
u/sciency_stuff Feb 17 '16
Decided I'd give it a quick attempt in python.
1
u/Kerndog73 Apr 18 '16 edited Apr 18 '16
JavaScript
invoke like this
At its current configuration the number of generations is around 20 or 30. It takes about 200ms to run. Here's a sample output after running it a bunch of times (57)
If you mess around with the constants you could probably get better and faster.
EDIT: Just realised that the challenge was asking for fastest and not least generations!
If you configure
POP_SIZE = 60, FITEST_SIZE = 10You could get about 16ms or 0.016s (better than /u/pantsforbirds !)
1
u/pacificjunction May 06 '16
Python3
Simple fitness function with variable population size. Two individuals with highest fitness in population are chosen to mate. Adjustable mutation rate. Can do any string given.
Output
0
u/[deleted] Jan 13 '16
[deleted] — view deleted comment
2
u/[deleted] Jan 14 '16 edited Jan 14 '16
[removed] — view removed comment