function Xeval=evaluation(X);
  [Npop,n2]=size(X);n=n2-1;
  Xeval=X;
  for i=1:Npop;
    Xeval(i,$)=sum(X(i,1:n).^2-cos(2*%pi*X(i,1:n)))+n;
end
endfunction
///////////////////////////////
function bestX=best(X);
[Npop,n2]=size(X);
[y,k]=sort(-X(:,$))
bestX=X(k(1),:);
endfunction
//////////////////////////////// 
function Xsel=selection(X)  // selection par le rang
[Npop,n2]=size(X);
[y,k]=sort(X(:,$))  
X=X(k,:);  
p=1:Npop;
roulette=cumsum(p)/sum(p);
Xsel=[];
for i=1:Npop
  u=rand();
  w=find(u<roulette);
  n1=w(1);
  xsel=X(n1,:);
  Xsel=[Xsel;xsel];
end  
endfunction
////////////////////////////////// 
function xcrois=croisement(x)
// x: 2 lignes
xcrois=x;
u=rand();
xcrois(1,:)=u*x(1,:)+(1-u)*x(2,:);
xcrois(2,:)=(1-u)*x(1,:)+u*x(2,:);
endfunction
//////////////////////////////////
function xmut=mutation(x)
// x: 1 ligne
u=rand(1,1,'n');
sigma=0.1;
xmut=x+sigma*u;
endfunction

//////////MAIN //////////////////////////
Npop=50;
Ngen=30;
n=2;
pc=0.9;
pm=0.6;
xmin=-5;xmax=5;
//
X=xmin+(xmax-xmin)*rand(Npop,n+1);
bestX=[];
for i=1:Ngen
X=evaluation(X);   // evaluation
X=selection(X);    // selection
bestX=[bestX;best(X)];
Xnew=[];
for j=1:Npop/2
   u1=int(Npop*rand())+1;
   u2=int(Npop*rand())+1;
   if (rand()<pc) then 
     Xnew=[Xnew;croisement(X([u1,u2],:))]; //croisement  
   else
     Xnew=[Xnew;X([u1,u2],:)];
   end  
end
for j=1:Npop
  if (rand()<pm) then
    Xnew(j,:)=mutation(Xnew(j,:));  // mutation
  end 
end  
X=Xnew;
end
//////////TRACE //////////////////////////
xbasc()
plot2d(1:Ngen,bestX(:,$))

  
  
  
  
  
  
 
  
  
  
  
  
  
  
  
  
  




