WeixiangYan/CodeTransOcean huggingface dataset:
Task: Evolutionary algorithm





Java: import java.util.Random;

public class EvoAlgo {
  static final String target = "METHINKS IT IS LIKE A WEASEL";
  static final char[] possibilities = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ".toCharArray();
  static int C = 100; 
  static double minMutateRate = 0.09;
  static int perfectFitness = target.length();
  private static String parent;
  static Random rand = new Random();

  private static int fitness(String trial){
    int retVal = 0;
    for(int i = 0;i < trial.length(); i++){
      if (trial.charAt(i) == target.charAt(i)) retVal++;
    }
    return retVal;
  }

  private static double newMutateRate(){
    return (((double)perfectFitness - fitness(parent)) / perfectFitness * (1 - minMutateRate));
  }

  private static String mutate(String parent, double rate){
    String retVal = "";
    for(int i = 0;i < parent.length(); i++){
      retVal += (rand.nextDouble() <= rate) ?
        possibilities[rand.nextInt(possibilities.length)]:
        parent.charAt(i);
    }
    return retVal;
  }
  
  public static void main(String[] args){
    parent = mutate(target, 1);
    int iter = 0;
    while(!target.equals(parent)){
      double rate = newMutateRate();
      iter++;
      if(iter % 100 == 0){
        System.out.println(iter +": "+parent+ ", fitness: "+fitness(parent)+", rate: "+rate);
      }
      String bestSpawn = null;
      int bestFit = 0;
      for(int i = 0; i < C; i++){
        String spawn = mutate(parent, rate);
        int fitness = fitness(spawn);
        if(fitness > bestFit){
          bestSpawn = spawn;
          bestFit = fitness;
        }
      }
      parent = bestFit > fitness(parent) ? bestSpawn : parent;
    }
    System.out.println(parent+", "+iter);
  }

}



Python: from string import letters
from random import choice, random
 
target  = list("METHINKS IT IS LIKE A WEASEL")
charset = letters + ' '
parent  = [choice(charset) for _ in range(len(target))]
minmutaterate  = .09
C = range(100)
 
perfectfitness = float(len(target))
    
def fitness(trial):
    'Sum of matching chars by position'
    return sum(t==h for t,h in zip(trial, target))
 
def mutaterate():
    'Less mutation the closer the fit of the parent'
    return 1-((perfectfitness - fitness(parent)) / perfectfitness * (1 - minmutaterate))
 
def mutate(parent, rate):
    return [(ch if random() <= rate else choice(charset)) for ch in parent]
 
def que():
    '(from the favourite saying of Manuel in Fawlty Towers)'
    print ("
           (iterations, fitness(parent)*100./perfectfitness, ''.join(parent)))

def mate(a, b):
    place = 0
    if choice(xrange(10)) < 7:
        place = choice(xrange(len(target)))
    else:
        return a, b
    
    return a, b, a[:place] + b[place:], b[:place] + a[place:]

iterations = 0
center = len(C)/2
while parent != target:
    rate = mutaterate()
    iterations += 1
    if iterations % 100 == 0: que()
    copies = [ mutate(parent, rate) for _ in C ]  + [parent]
    parent1 = max(copies[:center], key=fitness)
    parent2 = max(copies[center:], key=fitness)
    parent = max(mate(parent1, parent2), key=fitness)
que()
Task: Evolutionary algorithm





Java: import java.util.Random;

public class EvoAlgo {
  static final String target = "METHINKS IT IS LIKE A WEASEL";
  static final char[] possibilities = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ".toCharArray();
  static int C = 100; 
  static double minMutateRate = 0.09;
  static int perfectFitness = target.length();
  private static String parent;
  static Random rand = new Random();

  private static int fitness(String trial){
    int retVal = 0;
    for(int i = 0;i < trial.length(); i++){
      if (trial.charAt(i) == target.charAt(i)) retVal++;
    }
    return retVal;
  }

  private static double newMutateRate(){
    return (((double)perfectFitness - fitness(parent)) / perfectFitness * (1 - minMutateRate));
  }

  private static String mutate(String parent, double rate){
    String retVal = "";
    for(int i = 0;i < parent.length(); i++){
      retVal += (rand.nextDouble() <= rate) ?
        possibilities[rand.nextInt(possibilities.length)]:
        parent.charAt(i);
    }
    return retVal;
  }
  
  public static void main(String[] args){
    parent = mutate(target, 1);
    int iter = 0;
    while(!target.equals(parent)){
      double rate = newMutateRate();
      iter++;
      if(iter % 100 == 0){
        System.out.println(iter +": "+parent+ ", fitness: "+fitness(parent)+", rate: "+rate);
      }
      String bestSpawn = null;
      int bestFit = 0;
      for(int i = 0; i < C; i++){
        String spawn = mutate(parent, rate);
        int fitness = fitness(spawn);
        if(fitness > bestFit){
          bestSpawn = spawn;
          bestFit = fitness;
        }
      }
      parent = bestFit > fitness(parent) ? bestSpawn : parent;
    }
    System.out.println(parent+", "+iter);
  }

}




VB: Option explicit

Function rand(l,u) rand= Int((u-l+1)*Rnd+l): End Function

Function fitness(i)
  Dim d,j
  d=0
  For j=1 To lmod
     If Mid(model,j,1)=Mid(cpy(i),j,1) Then d=d+1
  Next
fitness=d
End Function

Sub mutate(i)
Dim j
 cpy(i)=""
 For j=1 To lmod
 If Rnd<mut Then 
  cpy(i)=cpy(i)& Chr(rand(lb,ub))
 Else
  cpy(i)=cpy(i)& Mid(cpy(0),j,1)
 End If
 Next
End sub 
  
Sub print(s): 
   On Error Resume Next
    WScript.stdout.WriteLine (s)  
   If  err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit
End Sub 

Dim model,lmod,ub,lb,c,cpy,fit,best,i,d,mut,cnt
model="METHINKS IT IS LIKE A WEASEL"
model=Replace(model," ","@")
lmod=Len(model)
Randomize Timer
ub=Asc("Z")
lb=Asc("@")
c=10
mut=.05
best=0
ReDim cpy(c)


For i=0 To lmod-1
 cpy(best)=cpy(best)& chr(rand(lb,ub))
Next
best=0
cnt=0
do
  cpy(0)=cpy(best)
  fit=0
  For i=1 To c
   mutate(i)  
   d=fitness(i)
   If d>fit Then fit=d:best=i  
  Next
  cnt=cnt+1
  If (fit=lmod) Or ((cnt mod 10)=0)  Then print cnt &" " & fit & " "& Replace (cpy(best),"@"," ") 
Loop While fit <>lmod
Task: Evolutionary algorithm




Go: package main

import (
    "fmt"
    "math/rand"
    "time"
)

var target = []byte("METHINKS IT IS LIKE A WEASEL")
var set = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ ")
var parent []byte

func init() {
    rand.Seed(time.Now().UnixNano())
    parent = make([]byte, len(target))
    for i := range parent {
        parent[i] = set[rand.Intn(len(set))]
    }
}


func fitness(a []byte) (h int) {
    
    for i, tc := range target {
        if a[i] != tc {
            h++
        }
    }
    return
}


func mutate(p, m []byte, r float64) {
    for i, ch := range p {
        if rand.Float64() < r {
            m[i] = set[rand.Intn(len(set))]
        } else {
            m[i] = ch
        }
    }
}

func main() {
    const c = 20 

    copies := make([][]byte, c)
    for i := range copies {
        copies[i] = make([]byte, len(parent))
    }

    fmt.Println(string(parent))
    for best := fitness(parent); best > 0; {
        for _, cp := range copies {
            mutate(parent, cp, .05)
        }
        for _, cp := range copies {
            fm := fitness(cp)
            if fm < best {
                best = fm
                copy(parent, cp)
                fmt.Println(string(parent))
            }
        }
    }
}




Python: from string import letters
from random import choice, random
 
target  = list("METHINKS IT IS LIKE A WEASEL")
charset = letters + ' '
parent  = [choice(charset) for _ in range(len(target))]
minmutaterate  = .09
C = range(100)
 
perfectfitness = float(len(target))
    
def fitness(trial):
    'Sum of matching chars by position'
    return sum(t==h for t,h in zip(trial, target))
 
def mutaterate():
    'Less mutation the closer the fit of the parent'
    return 1-((perfectfitness - fitness(parent)) / perfectfitness * (1 - minmutaterate))
 
def mutate(parent, rate):
    return [(ch if random() <= rate else choice(charset)) for ch in parent]
 
def que():
    '(from the favourite saying of Manuel in Fawlty Towers)'
    print ("
           (iterations, fitness(parent)*100./perfectfitness, ''.join(parent)))

def mate(a, b):
    place = 0
    if choice(xrange(10)) < 7:
        place = choice(xrange(len(target)))
    else:
        return a, b
    
    return a, b, a[:place] + b[place:], b[:place] + a[place:]

iterations = 0
center = len(C)/2
while parent != target:
    rate = mutaterate()
    iterations += 1
    if iterations % 100 == 0: que()
    copies = [ mutate(parent, rate) for _ in C ]  + [parent]
    parent1 = max(copies[:center], key=fitness)
    parent2 = max(copies[center:], key=fitness)
    parent = max(mate(parent1, parent2), key=fitness)
que()
Task: Evolutionary algorithm




Go: package main

import (
    "fmt"
    "math/rand"
    "time"
)

var target = []byte("METHINKS IT IS LIKE A WEASEL")
var set = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ ")
var parent []byte

func init() {
    rand.Seed(time.Now().UnixNano())
    parent = make([]byte, len(target))
    for i := range parent {
        parent[i] = set[rand.Intn(len(set))]
    }
}


func fitness(a []byte) (h int) {
    
    for i, tc := range target {
        if a[i] != tc {
            h++
        }
    }
    return
}


func mutate(p, m []byte, r float64) {
    for i, ch := range p {
        if rand.Float64() < r {
            m[i] = set[rand.Intn(len(set))]
        } else {
            m[i] = ch
        }
    }
}

func main() {
    const c = 20 

    copies := make([][]byte, c)
    for i := range copies {
        copies[i] = make([]byte, len(parent))
    }

    fmt.Println(string(parent))
    for best := fitness(parent); best > 0; {
        for _, cp := range copies {
            mutate(parent, cp, .05)
        }
        for _, cp := range copies {
            fm := fitness(cp)
            if fm < best {
                best = fm
                copy(parent, cp)
                fmt.Println(string(parent))
            }
        }
    }
}





VB: Option explicit

Function rand(l,u) rand= Int((u-l+1)*Rnd+l): End Function

Function fitness(i)
  Dim d,j
  d=0
  For j=1 To lmod
     If Mid(model,j,1)=Mid(cpy(i),j,1) Then d=d+1
  Next
fitness=d
End Function

Sub mutate(i)
Dim j
 cpy(i)=""
 For j=1 To lmod
 If Rnd<mut Then 
  cpy(i)=cpy(i)& Chr(rand(lb,ub))
 Else
  cpy(i)=cpy(i)& Mid(cpy(0),j,1)
 End If
 Next
End sub 
  
Sub print(s): 
   On Error Resume Next
    WScript.stdout.WriteLine (s)  
   If  err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit
End Sub 

Dim model,lmod,ub,lb,c,cpy,fit,best,i,d,mut,cnt
model="METHINKS IT IS LIKE A WEASEL"
model=Replace(model," ","@")
lmod=Len(model)
Randomize Timer
ub=Asc("Z")
lb=Asc("@")
c=10
mut=.05
best=0
ReDim cpy(c)


For i=0 To lmod-1
 cpy(best)=cpy(best)& chr(rand(lb,ub))
Next
best=0
cnt=0
do
  cpy(0)=cpy(best)
  fit=0
  For i=1 To c
   mutate(i)  
   d=fitness(i)
   If d>fit Then fit=d:best=i  
  Next
  cnt=cnt+1
  If (fit=lmod) Or ((cnt mod 10)=0)  Then print cnt &" " & fit & " "& Replace (cpy(best),"@"," ") 
Loop While fit <>lmod
Task: Evolutionary algorithm







Python: from string import letters
from random import choice, random
 
target  = list("METHINKS IT IS LIKE A WEASEL")
charset = letters + ' '
parent  = [choice(charset) for _ in range(len(target))]
minmutaterate  = .09
C = range(100)
 
perfectfitness = float(len(target))
    
def fitness(trial):
    'Sum of matching chars by position'
    return sum(t==h for t,h in zip(trial, target))
 
def mutaterate():
    'Less mutation the closer the fit of the parent'
    return 1-((perfectfitness - fitness(parent)) / perfectfitness * (1 - minmutaterate))
 
def mutate(parent, rate):
    return [(ch if random() <= rate else choice(charset)) for ch in parent]
 
def que():
    '(from the favourite saying of Manuel in Fawlty Towers)'
    print ("
           (iterations, fitness(parent)*100./perfectfitness, ''.join(parent)))

def mate(a, b):
    place = 0
    if choice(xrange(10)) < 7:
        place = choice(xrange(len(target)))
    else:
        return a, b
    
    return a, b, a[:place] + b[place:], b[:place] + a[place:]

iterations = 0
center = len(C)/2
while parent != target:
    rate = mutaterate()
    iterations += 1
    if iterations % 100 == 0: que()
    copies = [ mutate(parent, rate) for _ in C ]  + [parent]
    parent1 = max(copies[:center], key=fitness)
    parent2 = max(copies[center:], key=fitness)
    parent = max(mate(parent1, parent2), key=fitness)
que()


VB: Option explicit

Function rand(l,u) rand= Int((u-l+1)*Rnd+l): End Function

Function fitness(i)
  Dim d,j
  d=0
  For j=1 To lmod
     If Mid(model,j,1)=Mid(cpy(i),j,1) Then d=d+1
  Next
fitness=d
End Function

Sub mutate(i)
Dim j
 cpy(i)=""
 For j=1 To lmod
 If Rnd<mut Then 
  cpy(i)=cpy(i)& Chr(rand(lb,ub))
 Else
  cpy(i)=cpy(i)& Mid(cpy(0),j,1)
 End If
 Next
End sub 
  
Sub print(s): 
   On Error Resume Next
    WScript.stdout.WriteLine (s)  
   If  err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit
End Sub 

Dim model,lmod,ub,lb,c,cpy,fit,best,i,d,mut,cnt
model="METHINKS IT IS LIKE A WEASEL"
model=Replace(model," ","@")
lmod=Len(model)
Randomize Timer
ub=Asc("Z")
lb=Asc("@")
c=10
mut=.05
best=0
ReDim cpy(c)


For i=0 To lmod-1
 cpy(best)=cpy(best)& chr(rand(lb,ub))
Next
best=0
cnt=0
do
  cpy(0)=cpy(best)
  fit=0
  For i=1 To c
   mutate(i)  
   d=fitness(i)
   If d>fit Then fit=d:best=i  
  Next
  cnt=cnt+1
  If (fit=lmod) Or ((cnt mod 10)=0)  Then print cnt &" " & fit & " "& Replace (cpy(best),"@"," ") 
Loop While fit <>lmod
Task: Evolutionary algorithm

C: #include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char target[] = "METHINKS IT IS LIKE A WEASEL";
const char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ";

#define CHOICE (sizeof(tbl) - 1)
#define MUTATE 15
#define COPIES 30


int irand(int n)
{
	int r, rand_max = RAND_MAX - (RAND_MAX % n);
	while((r = rand()) >= rand_max);
	return r / (rand_max / n);
}


int unfitness(const char *a, const char *b)
{
	int i, sum = 0;
	for (i = 0; a[i]; i++)
		sum += (a[i] != b[i]);
	return sum;
}


void mutate(const char *a, char *b)
{
	int i;
	for (i = 0; a[i]; i++)
		b[i] = irand(MUTATE) ? a[i] : tbl[irand(CHOICE)];

	b[i] = '\0';
}

int main()
{
	int i, best_i, unfit, best, iters = 0;
	char specimen[COPIES][sizeof(target) / sizeof(char)];

	
	for (i = 0; target[i]; i++)
		specimen[0][i] = tbl[irand(CHOICE)];
	specimen[0][i] = 0;

	do {
		for (i = 1; i < COPIES; i++)
			mutate(specimen[0], specimen[i]);

		
		for (best_i = i = 0; i < COPIES; i++) {
			unfit = unfitness(target, specimen[i]);
			if(unfit < best || !i) {
				best = unfit;
				best_i = i;
			}
		}

		if (best_i) strcpy(specimen[0], specimen[best_i]);
		printf("iter %d, score %d: %s\n", iters++, best, specimen[0]);
	} while (best);

	return 0;
}






PHP: define('TARGET','METHINKS IT IS LIKE A WEASEL');
define('TBL','ABCDEFGHIJKLMNOPQRSTUVWXYZ ');

define('MUTATE',15);
define('COPIES',30);
define('TARGET_COUNT',strlen(TARGET));
define('TBL_COUNT',strlen(TBL));


function unfitness($a,$b)
{
        $sum=0;
        for($i=0;$i<strlen($a);$i++)
                if($a[$i]!=$b[$i]) $sum++;
        return($sum);
}

function mutate($a)
{
        $tbl=TBL;
        for($i=0;$i<strlen($a);$i++) $out[$i]=mt_rand(0,MUTATE)?$a[$i]:$tbl[mt_rand(0,TBL_COUNT-1)];
        return(implode('',$out));
}


$tbl=TBL;
for($i=0;$i<TARGET_COUNT;$i++) $tspec[$i]=$tbl[mt_rand(0,TBL_COUNT-1)];
$parent[0]=implode('',$tspec);
$best=TARGET_COUNT+1;
$iters=0;
do {
        for($i=1;$i<COPIES;$i++) $parent[$i]=mutate($parent[0]);

        for($best_i=$i=0; $i<COPIES;$i++) {
                $unfit=unfitness(TARGET,$parent[$i]);
                if($unfit < $best || !$i) {
                        $best=$unfit;
                        $best_i=$i;
                }
        }
        if($best_i>0) $parent[0]=$parent[$best_i];
        $iters++;
        print("Generation $iters, score $best: $parent[0]\n");
} while($best);
Task: Evolutionary algorithm



C#: using System;
using System.Collections.Generic;
using System.Linq;

static class Program {
    static Random Rng = new Random((int)DateTime.Now.Ticks);

    static char NextCharacter(this Random self) {
        const string AllowedChars = " ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        return AllowedChars[self.Next() % AllowedChars.Length];
    }

    static string NextString(this Random self, int length) {
        return String.Join("", Enumerable.Repeat(' ', length)
            .Select(c => Rng.NextCharacter()));
    }

    static int Fitness(string target, string current) {
        return target.Zip(current, (a, b) => a == b ? 1 : 0).Sum();
    }

    static string Mutate(string current, double rate) {
        return String.Join("", from c in current
               select Rng.NextDouble() <= rate ? Rng.NextCharacter() : c);
    }

    static void Main(string[] args) {
        const string target = "METHINKS IT IS LIKE A WEASEL";
        const int C = 100;
        const double P = 0.05;

        
        string parent = Rng.NextString(target.Length);

        Console.WriteLine("START:       {0,20} fitness: {1}", 
            parent, Fitness(target, parent));
        int i = 0;

        while (parent != target) {
            
            var candidates = Enumerable.Range(0, C + 1)
                .Select(n => n > 0 ? Mutate(parent, P) : parent);

            
            parent = candidates.OrderByDescending(c => Fitness(target, c)).First();

            ++i;
            Console.WriteLine("     #{0,6} {1,20} fitness: {2}", 
                i, parent, Fitness(target, parent));
        }

        Console.WriteLine("END: #{0,6} {1,20}", i, parent);
    }
}




PHP: define('TARGET','METHINKS IT IS LIKE A WEASEL');
define('TBL','ABCDEFGHIJKLMNOPQRSTUVWXYZ ');

define('MUTATE',15);
define('COPIES',30);
define('TARGET_COUNT',strlen(TARGET));
define('TBL_COUNT',strlen(TBL));


function unfitness($a,$b)
{
        $sum=0;
        for($i=0;$i<strlen($a);$i++)
                if($a[$i]!=$b[$i]) $sum++;
        return($sum);
}

function mutate($a)
{
        $tbl=TBL;
        for($i=0;$i<strlen($a);$i++) $out[$i]=mt_rand(0,MUTATE)?$a[$i]:$tbl[mt_rand(0,TBL_COUNT-1)];
        return(implode('',$out));
}


$tbl=TBL;
for($i=0;$i<TARGET_COUNT;$i++) $tspec[$i]=$tbl[mt_rand(0,TBL_COUNT-1)];
$parent[0]=implode('',$tspec);
$best=TARGET_COUNT+1;
$iters=0;
do {
        for($i=1;$i<COPIES;$i++) $parent[$i]=mutate($parent[0]);

        for($best_i=$i=0; $i<COPIES;$i++) {
                $unfit=unfitness(TARGET,$parent[$i]);
                if($unfit < $best || !$i) {
                        $best=$unfit;
                        $best_i=$i;
                }
        }
        if($best_i>0) $parent[0]=$parent[$best_i];
        $iters++;
        print("Generation $iters, score $best: $parent[0]\n");
} while($best);
Task: Evolutionary algorithm




Go: package main

import (
    "fmt"
    "math/rand"
    "time"
)

var target = []byte("METHINKS IT IS LIKE A WEASEL")
var set = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ ")
var parent []byte

func init() {
    rand.Seed(time.Now().UnixNano())
    parent = make([]byte, len(target))
    for i := range parent {
        parent[i] = set[rand.Intn(len(set))]
    }
}


func fitness(a []byte) (h int) {
    
    for i, tc := range target {
        if a[i] != tc {
            h++
        }
    }
    return
}


func mutate(p, m []byte, r float64) {
    for i, ch := range p {
        if rand.Float64() < r {
            m[i] = set[rand.Intn(len(set))]
        } else {
            m[i] = ch
        }
    }
}

func main() {
    const c = 20 

    copies := make([][]byte, c)
    for i := range copies {
        copies[i] = make([]byte, len(parent))
    }

    fmt.Println(string(parent))
    for best := fitness(parent); best > 0; {
        for _, cp := range copies {
            mutate(parent, cp, .05)
        }
        for _, cp := range copies {
            fm := fitness(cp)
            if fm < best {
                best = fm
                copy(parent, cp)
                fmt.Println(string(parent))
            }
        }
    }
}



PHP: define('TARGET','METHINKS IT IS LIKE A WEASEL');
define('TBL','ABCDEFGHIJKLMNOPQRSTUVWXYZ ');

define('MUTATE',15);
define('COPIES',30);
define('TARGET_COUNT',strlen(TARGET));
define('TBL_COUNT',strlen(TBL));


function unfitness($a,$b)
{
        $sum=0;
        for($i=0;$i<strlen($a);$i++)
                if($a[$i]!=$b[$i]) $sum++;
        return($sum);
}

function mutate($a)
{
        $tbl=TBL;
        for($i=0;$i<strlen($a);$i++) $out[$i]=mt_rand(0,MUTATE)?$a[$i]:$tbl[mt_rand(0,TBL_COUNT-1)];
        return(implode('',$out));
}


$tbl=TBL;
for($i=0;$i<TARGET_COUNT;$i++) $tspec[$i]=$tbl[mt_rand(0,TBL_COUNT-1)];
$parent[0]=implode('',$tspec);
$best=TARGET_COUNT+1;
$iters=0;
do {
        for($i=1;$i<COPIES;$i++) $parent[$i]=mutate($parent[0]);

        for($best_i=$i=0; $i<COPIES;$i++) {
                $unfit=unfitness(TARGET,$parent[$i]);
                if($unfit < $best || !$i) {
                        $best=$unfit;
                        $best_i=$i;
                }
        }
        if($best_i>0) $parent[0]=$parent[$best_i];
        $iters++;
        print("Generation $iters, score $best: $parent[0]\n");
} while($best);
Task: Evolutionary algorithm





Java: import java.util.Random;

public class EvoAlgo {
  static final String target = "METHINKS IT IS LIKE A WEASEL";
  static final char[] possibilities = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ".toCharArray();
  static int C = 100; 
  static double minMutateRate = 0.09;
  static int perfectFitness = target.length();
  private static String parent;
  static Random rand = new Random();

  private static int fitness(String trial){
    int retVal = 0;
    for(int i = 0;i < trial.length(); i++){
      if (trial.charAt(i) == target.charAt(i)) retVal++;
    }
    return retVal;
  }

  private static double newMutateRate(){
    return (((double)perfectFitness - fitness(parent)) / perfectFitness * (1 - minMutateRate));
  }

  private static String mutate(String parent, double rate){
    String retVal = "";
    for(int i = 0;i < parent.length(); i++){
      retVal += (rand.nextDouble() <= rate) ?
        possibilities[rand.nextInt(possibilities.length)]:
        parent.charAt(i);
    }
    return retVal;
  }
  
  public static void main(String[] args){
    parent = mutate(target, 1);
    int iter = 0;
    while(!target.equals(parent)){
      double rate = newMutateRate();
      iter++;
      if(iter % 100 == 0){
        System.out.println(iter +": "+parent+ ", fitness: "+fitness(parent)+", rate: "+rate);
      }
      String bestSpawn = null;
      int bestFit = 0;
      for(int i = 0; i < C; i++){
        String spawn = mutate(parent, rate);
        int fitness = fitness(spawn);
        if(fitness > bestFit){
          bestSpawn = spawn;
          bestFit = fitness;
        }
      }
      parent = bestFit > fitness(parent) ? bestSpawn : parent;
    }
    System.out.println(parent+", "+iter);
  }

}


PHP: define('TARGET','METHINKS IT IS LIKE A WEASEL');
define('TBL','ABCDEFGHIJKLMNOPQRSTUVWXYZ ');

define('MUTATE',15);
define('COPIES',30);
define('TARGET_COUNT',strlen(TARGET));
define('TBL_COUNT',strlen(TBL));


function unfitness($a,$b)
{
        $sum=0;
        for($i=0;$i<strlen($a);$i++)
                if($a[$i]!=$b[$i]) $sum++;
        return($sum);
}

function mutate($a)
{
        $tbl=TBL;
        for($i=0;$i<strlen($a);$i++) $out[$i]=mt_rand(0,MUTATE)?$a[$i]:$tbl[mt_rand(0,TBL_COUNT-1)];
        return(implode('',$out));
}


$tbl=TBL;
for($i=0;$i<TARGET_COUNT;$i++) $tspec[$i]=$tbl[mt_rand(0,TBL_COUNT-1)];
$parent[0]=implode('',$tspec);
$best=TARGET_COUNT+1;
$iters=0;
do {
        for($i=1;$i<COPIES;$i++) $parent[$i]=mutate($parent[0]);

        for($best_i=$i=0; $i<COPIES;$i++) {
                $unfit=unfitness(TARGET,$parent[$i]);
                if($unfit < $best || !$i) {
                        $best=$unfit;
                        $best_i=$i;
                }
        }
        if($best_i>0) $parent[0]=$parent[$best_i];
        $iters++;
        print("Generation $iters, score $best: $parent[0]\n");
} while($best);