% Simulated Annealing low-autocorrelation program
% BSDLicence
% Rick van der Zwet - 0433373 - <hvdzwet@liacs.nl>
% $Id: sa.m 44 2009-12-17 22:23:16Z rick $

function [iteration_history,fitness_history] = sa(seq, stopLimit)
  fitness = 0;
  temperature = stopLimit;

  iteration_history = [];
  fitness_history = [];

  for iteration = 1:stopLimit
    % Generate new mutation
    newseq = mutation(seq);

    new_fitness = autocorrelation(newseq);

    % Better is always accept
    if (new_fitness > fitness)
      fitness = new_fitness;
      % disp(rot90(newseq,-1));
      temperature = temperature - 10;
    else
      % Make the next 'move' less atractive
      temperature = temperature + 1;

      % Accept on an certain probability
      if (temperature < 1)
        break;
      else 
        % XXX: Some more cleaver cooling would be great
        if( exp(1)^((fitness - new_fitness) / temperature) > rand())
          seq = newseq;
         end
       end
    end
    iteration_history = [ iteration_history, iteration ];
    fitness_history = [ fitness_history, fitness ]; 
  end
end
