Npop=40;
L=30;
Ngen=200;
pc=0.6;
pm=0.04;
//
function y=J(C)
   y=sum(C)
endfunction 
//
// initialisation
A=int(2*rand(Npop,L+1));
//
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*rand()+1);
    u2=int(Npop*rand()+1);
    if (rand()<pc) then
      u=int((L-1)*rand()+1);
      uenf1=[Asel(u1,1:u),Asel(u2,u+1:L+1)];
      uenf2=[Asel(u2,1:u),Asel(u1,u+1:L+1)];
    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
    for j=1:L
      if (rand()<pm) then
         Amut(k,j)=1-Amut(k,j);
      end
    end
  end
A=Amut;
end  
//
for i=1:Npop
  A(i,L+1)=J(A(i,1:L));
end
[s,p]=sort(A(:,L+1));
A=A(p,:);
disp(A(Npop,1:L))
