function Asel=tournoi(A)
    [Npop,n1]=size(A)
    Asel=A
    for i=1:Npop
        u=1+floor(rand()*Npop);
        v=1+floor(rand()*Npop);
      if (A(u,n1)>A(v,n1)) then
         Asel(i,:)=A(v,:) 
      else
       Asel(i,:)=A(u,:) 
     end  
    end
endfunction
//
function Amut=mutation(A,pm,alpha)
        [Npop,n1]=size(A);
        Amut=A;
       for i=1:Npop
         if rand()<pm then
          for j=1:n1-1
           Amut(i,j)=A(i,j)+2*alpha*(rand()-0.5) 
          end 
         end 
        end       
endfunction
//
function Acrois=croisement(A,pc)
       [Npop,n1]=size(A);
       Acrois=A;
       for i=1:Npop/2
        u=1+floor(rand()*Npop);
        v=1+floor(rand()*Npop);
        r=rand()
        if (rand()<pc)
         Acrois(2*i-1,:)=r*A(u,:)+(1-r)*A(v,:)
         Acrois(2*i,:)=(1-r)*A(u,:)+r*A(v,:) 
        else
         Acrois(2*i-1,:)=A(u,:)
         Acrois(2*i,:)=A(v,:)             
        end       
      end
endfunction
//
function y=rastrigin(x)  // the function to optimize
n1=length(x);
y=n1+sum(x.^2-cos(2*%pi*x));
endfunction
///////////////////////
Npop=40;Ngen=30;pm=0.9;pc=0.6;alpha=0.1;n=2;
// initialisation
A=10*rand(Npop,n+1)-3*ones(Npop,n+1)
//
Jmin=[];
figure(1);
for i=1:Ngen
    drawlater
    clf()
    plot2d(A(:,1),A(:,2),-1,rect=[-3,-3,7,7])
    drawnow
 //   pause
    //eval
    for j=1:Npop
       A(j,n+1)=rastrigin(A(j,1:n)) 
    end   
    c=gsort(A(:,n+1));
// 
    Jmin=[Jmin,c(Npop)]
    // selection
    Asel=tournoi(A)    
    // croisement
    Acrois=croisement(Asel,pc)
    // mutation
    Amut=mutation(Acrois,pm,alpha)
A=Amut;    
end
xtitle('evolution de la population')
figure(2)
clf()
plot(1:Ngen,Jmin)
xtitle('meilleur valeur obtenue pour la fonction J')

















