Last active
May 5, 2018 05:05
-
-
Save sharavsambuu/0bf9a264b9d4db2fd1bcfc51dddf484e to your computer and use it in GitHub Desktop.
Hello World, Genetic Algorithm: https://www.electricmonk.nl/log/2011/09/28/evolutionary-algorithm-evolving-hello-world/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # source : https://www.electricmonk.nl/log/2011/09/28/evolutionary-algorithm-evolving-hello-world/ | |
| import random | |
| import string | |
| source = "jijvdvnmertnj" | |
| target = "Hello, World!" | |
| def calc_fitness(source, target): | |
| fitval = 0 | |
| for i in range(0, len(source)): | |
| fitval += (ord(target[i]) - ord(source[i])) ** 2 | |
| return fitval | |
| GEN_SIZE = 20 | |
| genepool = [] | |
| for i in range(0, GEN_SIZE): | |
| dna = [random.choice(string.printable[:-5]) for j in range(0, len(target))] | |
| fitness = calc_fitness(dna, target) | |
| candidate = {'dna': dna, 'fitness': fitness} | |
| genepool.append(candidate) | |
| def mutate(parent1, parent2): | |
| child_dna = parent1['dna'][:] | |
| # mix both dnas | |
| start = random.randint(0, len(parent2['dna'])-1) | |
| stop = random.randint(0, len(parent2['dna'])-1) | |
| if start>stop: | |
| stop, start = start, stop | |
| child_dna[start:stop] = parent2['dna'][start:stop] | |
| # mutate one position | |
| charpos = random.randint(0, len(child_dna)-1) | |
| child_dna[charpos] = chr(ord(child_dna[charpos])+random.randint(-1,1)) | |
| child_fitness = calc_fitness(child_dna, target) | |
| return ({'dna': child_dna, 'fitness': child_fitness}) | |
| def random_parent(genepool): | |
| wRndNr = random.random()*random.random()*(GEN_SIZE-1) | |
| wRndNr = int(wRndNr) | |
| return (genepool[wRndNr]) | |
| while True: | |
| genepool.sort(key=lambda candidate: candidate['fitness']) | |
| if genepool[0]['fitness'] == 0: | |
| print("Target reached") | |
| print(str(genepool[0]['dna'])) | |
| break | |
| parent1 = random_parent(genepool) | |
| parent2 = random_parent(genepool) | |
| child = mutate(parent1, parent2) | |
| if child['fitness'] < genepool[-1]['fitness']: | |
| genepool[-1] = child |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment