## Author: M. Turhan ÇOBAN
## Created: 2021-11-07
## Genetic optimisation using binary genes 0010011100101000111..
## iterative_hill_climbing_opt

function [BestX BestY] =iterative_hill_climbing_opt(fx,xmin,xmax,MAXIMUM,n_neigbour,r)
## r radius factor (neigbouring ratio)
## n_neighbour: number of neighbour points
## MAXIMUM: number of trials
## xmin minimum values of search region
## xmax maximum values of search region
## fx search function
n=length(xmin);
fmax=-realmax('double');
for j=1:n
      dx(j)=(xmax(j)-xmin(j));
endfor
for t=1:MAXIMUM
   ## select a random point vc 
   for j=1:n
      vc(j)=xmin(j)+dx(j)*rand;
   endfor # for j=1:n
   ## calculate the function for vc 
   fc=fx(vc);
   if fc>fmax
     fmax=fc;
     vmax=vc;
   endif # if fc>fmax
   for k=1:n_neigbour
      for j=1:n
         vn(j)=vc(j)+dx(j)*r*rand;
         if vn(j)<xmin(j) 
           vn(j)=xmin(j);
         elseif vn(j)>xmax(j) 
           vn(j)=xmin(j);          
         endif # if vn(j)<xmin(j) 
      endfor # for j=1:n
      fn=fx(vn);
      if fn>fc
        vc=vn;
        fc=fn;
        break;
      endif # if fn>fc
      if fc>fmax
         fmax=fc;
         vmax=vc;
      endif # if fc>fmax
   endfor  # k=1:n_neighbour
# printf('%i generation %i population \n',t);
# printf('%i %d %d %d \n',t,vmax ,fmax);
endfor # for t=1:MAXIMUM
BestX=vmax;
BestY=fmax;  
endfunction