function [] = simulated_annealing(X, Y) % simulated annealing applied to TSP

% Just to be sure...
if length(X) ~= length(Y)
    error('X and Y must be vectors of the same length');
else
    N = length(X);
end

% Initialize simulated annealing parameters
temp = 10;
cooling_rate = .999;
curr_X = X;
curr_Y = Y;
curr_cost = tour_dist([X Y]);
iter = 0;

% Begin search algorithm
while temp > 1e-2
    
    % We begin with the current configuration...
    X = curr_X;
    Y = curr_Y;
    
    % Randomly select two cities to swap
    city1 = randi(N);
    city2 = randi(N);
    
    % Swap these two cities
    tmp = X(city1);
    X(city1) = X(city2);
    X(city2) = tmp;
    
    tmp = Y(city1);
    Y(city1) = Y(city2);
    Y(city2) = tmp;
    
    % Compute the cost of the new tour
    new_cost = tour_dist([X Y]);
    
    % New tour is better than curr tour
    if (new_cost <= curr_cost) 
        curr_X = X;
        curr_Y = Y;
        curr_cost = new_cost;
        
    % New tour is worse...accept with some probability 
    elseif rand() <= exp((curr_cost - new_cost)/temp)
        disp(sprintf('\tAccepted with prob %f', exp((curr_cost - new_cost)/temp)));
        curr_X = X;
        curr_Y = Y;
        curr_cost = new_cost;            
    end
    
    % Update the temperature
    temp = temp*cooling_rate;
    iter = iter + 1;
   
    if mod(iter, 100) == 0
        disp(sprintf('Iter %d', iter));
        disp(sprintf('\tTemp = %f ', temp));
        disp(sprintf('\tCost = %f \n', curr_cost));
        plot_tour(curr_X, curr_Y);        
        pause(.3);
    end
end


