diff --git a/hellogene.py b/hellogene.py new file mode 100644 index 0000000..e70cda7 --- /dev/null +++ b/hellogene.py @@ -0,0 +1,37 @@ +import random, string + +GA_POPSIZE = 2048 +GA_ELITRATE= 0.10 # elitism rate +GA_MUTATIONRATE = 0.25 # mutation rate +GA_TARGET = "Hello world!" +GA_CHARS = string.ascii_lowercase + string.digits + string.punctuation + string.whitespace +string.ascii_uppercase + +def randstr(): + return "".join([random.choice(GA_CHARS) for i in range(len(GA_TARGET))]) + +def fitness(value): + return sum([abs(ord(value[j]) - ord(GA_TARGET[j])) for j in range(len(GA_TARGET))]) + +def mate(population, buffer): + esize = int(GA_POPSIZE * GA_ELITRATE) + for i in range(esize): # Elitism + buffer[i] = population[i] + for i in range(esize, GA_POPSIZE): + i1 = random.randint(0, GA_POPSIZE / 2) + i2 = random.randint(0, GA_POPSIZE / 2) + spos = random.randint(0, len(GA_TARGET)) + buffer[i] = population[i1][:spos] + population[i2][spos:] # Mate + if random.random() < GA_MUTATIONRATE: # Mutate + pos = random.randint(0, len(GA_TARGET)-1) + buffer[i] = buffer[i][:pos] + random.choice(GA_CHARS) + buffer[i][pos+1:] + +population = [randstr() for i in range(GA_POPSIZE)] +buffer = [randstr() for i in range(GA_POPSIZE)] +while True: + i+=1; + population = sorted(population, key=lambda c: fitness(c)) + print (("round: %d variation: %d string generated: %s") % (i, fitness(population[0]), population[0])) + if not fitness(population[0]): # We're done, best match found + break + mate(population, buffer) + population, buffer = buffer, population