clear;
A=10; B=22;

crossprob=0.8
mutprob=0.08
elit=2;

xx=10:0.1:22;
yy=(xx.^2-28*xx+180).*sin(xx./(3+cos(2*xx)))+35;
codelen=8;  popsize=12;
pop=round(rand(popsize+elit,codelen));

for k= 1: 10
    bin2dec(int2str(pop));
    % OCTAVE bin2dec(num2str(pop,'%d'));

    x=A + (B-A)*bin2dec(int2str(pop))./(2^codelen-1);
    % OCTAVE x=A + (B-A)*bin2dec(num2str(pop,'%d'))./(2^codelen-1)

    % vyhodnotenie
    y=(x.^2-28*x+180).*sin(x./(3+cos(2*x)))+35;
    MAX=max(y)
    MEAN=sum(y)/size(y,1)
    
    % elitizmus
    [sorted,Ind]=sort(y);
    % disp(Ind(popsize+1 : popsize+elit));
    for j=popsize+1 : popsize+elit
        hlp               = pop(Ind(j),:);
        pop(Ind(j),:) = pop(j,:);
        pop(j,:)          = hlp;
    end
    
    plot(x,y,'o',xx,yy)
    CUMSUM=cumsum(y);
    SUM=sum(y);

    % selekcia
    pause(0.2)

    prob=cumsum(y)/sum(y);

    for i= 1 : popsize
        newpop(i,:)=pop(find((prob>=rand),1,'first'),:);
        %OCTAVE    newpop(i,:)=pop(min(find(prob>=rand)),:);
    end

    %newpop
    % pause

    for i=1 : popsize/2
        if rand<=crossprob
            % newpop(2*i-1,:)
            % newpop(2*i,:)
            c=floor((codelen-1)*rand)+1;
            % display([num2str(2*i-1) '-' num2str(2*i) ' crossing at ' num2str(c)]);
            pop(2*i-1,:)=[newpop(2*i-1,1:c) newpop(2*i,c+1:codelen)];
            pop(2*i,:)=[newpop(2*i,1:c) newpop(2*i-1,c+1:codelen)];
        else
            % display([num2str(2*i-1) '-' num2str(2*i) 'no crossing']);
            pop(2*i-1,:)=newpop(2*i-1,:);
            pop(2*i,:)=newpop(2*i,:);
        end
    % pause
    end
    
    % mutacia
    % pop1=pop
    for i=1:popsize
        for j= 1:codelen
            if rand<=mutprob
                pop(i,j)=1-pop(i,j);
            end
        end
    end
    % pop-pop1
   
end

bin2dec(int2str(pop))
% OCTAVE bin2dec(num2str(pop,'%d'));

x=A + (B-A)*bin2dec(int2str(pop))./(2^codelen-1);
% OCTAVE x=A + (B-A)*bin2dec(num2str(pop,'%d'))./(2^codelen-1)

% vyhodnotenie
y=(x.^2-28*x+180).*sin(x./(3+cos(2*x)))+35-35;
MAX=max(y)
MEAN=sum(y)/size(y,1)

[sorted,Ind]=sort(y);
disp(['Maximum je v bode ',num2str(x(Ind(popsize+elit)))])

plot(x,y,'o',xx,yy-35)