clear all;
close all;
clc;

n=8; %number of cities
%A=[0,10,40,5;10,0,5,20;40,5,0,30;5,20,30,0] %
A=createTSP(n);

%Brute Force Search
%-------------------------------------------------------------------
tic;
nodes=[2:n];
perm=perms(nodes); %All possible permutations
noOfPerm=factorial(n-1);
perm=[ones(noOfPerm,1),perm];
for i=1:noOfPerm-1
    for j=1:n-1
        W(i,j)=A(perm(i,j),perm(i,j+1)); %calculates the cost of each path
    end
end
[minW,minIndex]=min(sum(W,2));
bestPath=perm(minIndex,1:n) %
algo1Time=toc

% 2opt Algorithm 
%-----------------------------------------------------------------------
tic
bestPath2=[1:n];
tempPath=bestPath2;
K=1;Z=1;
count=1;

for i=1:1000
    tempPath=bestPath2; 
    K=round(mod(rand*100,n-2))+2
    Z=round(mod(rand*100,n-2))+2;
    
    temp=tempPath(K);
    tempPath(K)=tempPath(Z);
    tempPath(Z)=temp;
    if cost(tempPath,A)<cost(bestPath2,A)
        bestPath2=tempPath ;   
    end
    hold on;
    plot(i,cost(bestPath2,A))
    
%     count=count+1
%     K
%     Z
end
toc;
algo2Time=toc;
bestPath %diplaying best path via brute force searech
bestPath2% displaying best path via 2-opt algorithm
cost(bestPath,A)
cost(bestPath2,A)


%---------------------------------------------------



cK=nchoosek(2:n,2)
sizecK=size(cK);
randIndex=randperm(sizecK(1,1))
cK=cK(randIndex,:)%matrix of random breaking points

bestPath2=[1:n];
tempPath=bestPath2;
K=1;Z=1;
for i=1:sizecK(1,1)

    tempPath=bestPath2;     
    K=cK(i,1);
    Z=cK(i,2);
    temp=tempPath(K);
    tempPath(K)=tempPath(Z);
    tempPath(Z)=temp;
    if cost(tempPath,A)<cost(bestPath2,A)
        bestPath2=tempPath ;
        i=1;
    end
    hold on;
    plot(i,cost(bestPath2,A))
    

end
%bestPath2=[1,bestPath2]



