////////////////////
//
//  M7: AG a partir de AG binaire
// minimisation de la fonction de Rastrigin a 6 variables sur [-5,5]
//
///////////////////
//
Npop=200;
L=6;
Ngen=100;
pc=0.6;
pm=0.2;
sigma=0.1;
//
function y=J(C)
   y=C*C'-sum(cos(2*%pi*C))
endfunction 
//
// initialisation
A=10*rand(Npop,L+1)-5;
//
for i=1:Ngen
// evaluation
for i=1:Npop
  A(i,L+1)=J(A(i,1:L));
end
// selection
// 1st step: sort elements
[s,p]=gsort(A(:,L+1));
A=A(p,:);
// 2st step: choose Npop elements with probability pi
//
Asel=[];
p=(1:Npop)/sum(1:Npop);ps=cumsum(p);
for i=1:Npop
  u=rand();isel=1;
  while (u>ps(isel)) 
     isel=isel+1;
  end
Asel=[Asel;A(isel,:)];
end  
// crossover  
Acrois=[];
  for k=1:Npop/2
      u1=int((Npop-1)*rand()+1);
      u2=int((Npop-1)*rand()+1);
    if (rand()<pc) then
      u=rand();
      uenf1=u*Asel(u1,:)+(1-u)*Asel(u2,:);
      uenf2=u*Asel(u2,:)+(1-u)*Asel(u1,:);
    else
      uenf1=Asel(u1,1:L+1);
      uenf2=Asel(u2,1:L+1);
    end   
    Acrois=[Acrois;uenf1;uenf2];
   end 
// mutation   
Amut=Acrois;
for k=1:Npop
    if (rand()<pm) then
      Amut(k,1:L)=Amut(k,1:L)+sigma*rand(1,L,'n');
    end
  end
A=Amut;
end  
//
for i=1:Npop
  A(i,L+1)=J(A(i,1:L));
end
[s,p]=gsort(A(:,L+1));
A=A(p,:);
disp('meilleure solution:');
disp(A(Npop,1:L))
