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);
    }
}








Fortran:  
 	module evolve_routines
 
 	implicit none
 	
 	
 	character(len=*),parameter :: targ = 'METHINKS IT IS LIKE A WEASEL'
 	
 	contains
 
 	
 
 	pure elemental function fitness(member) result(n)
 
 
 
 
 	
 	implicit none
 	integer :: n
 	character(len=*),intent(in) :: member
 	
 	integer :: i
 	
 	n=0
 	do i=1,len(targ)
 		n = n + abs( ichar(targ(i:i)) - ichar(member(i:i))  )
 	end do
 	
 
 	end function fitness
 
 	
 
 	pure elemental subroutine mutate(member,factor)
 
 
 
 	
 	implicit none
 	character(len=*),intent(inout) :: member   
 	real,intent(in) :: factor                  
 	
 	integer,parameter :: n_chars = 27	
 	character(len=n_chars),parameter :: chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ '
 	
 	real    :: rnd_val
 	integer :: i,j,n
 	
 	n = len(member)
 		
 	do i=1,n
 		rnd_val = rand()
 		if (rnd_val<=factor) then   
 			rnd_val = rand()
 			j = int(rnd_val*n_chars)+1   
 			member(i:i) = chars(j:j)
 		end if
 	end do
 	
 
	end subroutine mutate
 

 
 	end module evolve_routines
 
 
 
 	program evolve
 
 
 
 	use evolve_routines
 	
 	implicit none
 	
 	
 	integer,parameter :: seed = 12345             
 	integer,parameter :: max_iter = 10000         
 	integer,parameter :: population_size = 200    
 	real,parameter    :: factor = 0.04            
 	integer,parameter :: iprint = 5               
 	
 	
 	integer :: i,iter
 	integer,dimension(1) :: i_best
 	character(len=len(targ)),dimension(population_size) :: population
 	
 	
 	call srand(seed)
 	
 	
 	
 	population(1) = 'PACQXJB CQPWEYKSVDCIOUPKUOJY'  
 	iter=0
 		
 	write(*,'(A10,A30,A10)') 'iter','best','fitness'
 	write(*,'(I10,A30,I10)') iter,population(1),fitness(population(1))
 		
 	do 
 	
 		iter = iter + 1 
 		
  		
 		if (mod(iter,iprint)==0) write(*,'(I10,A30,I10)') iter,population(1),fitness(population(1))
		
 		
 		if ( iter>max_iter .or. fitness(population(1))==0 ) exit
 	
 		
 		population = population(1)	
 		do i=2,population_size
 			call mutate(population(i),factor)	
 		end do
 	
 		
 		
 		i_best = minloc(fitness(population))
 		population(1) = population(i_best(1))
 		 	
 	end do
 	
 	
 	if (mod(iter,iprint)/=0) write(*,'(I10,A30,I10)') iter,population(1),fitness(population(1))
 	 	
 	if (iter>max_iter) then
 		write(*,*) 'No solution found.'
 	else
 		write(*,*) 'Solution found.'
 	end if
 	
 
 	end program evolve