CITY_SIZE = 52;
CITIES = [565,575,25,185,345,750,945,685,845,655,880,660,25,230,525,1000,580,1175,650,1130,1605,620,1220,580 , 1465,200 , 1530,5 , 845,680 , 725,370 , 145,665 ,415,635 , 510,875 , 560,365 , 300,465 , 520,585 , 480,415 ,835,625 , 975,580 , 1215,245 , 1320,315 , 1250,400 , 660,180 ,410,250 , 420,555 , 575,665 , 1150,1160 , 700,580 , 685,595 ,685,610 , 770,610 , 795,645 , 720,635 , 760,650 , 475,960 ,95,260 , 875,920 , 700,500 , 555,815 , 830,485 , 1170,65 ,830,610,605,625,595,360,1340,725,1740,245 ];
CITIES = matrix(CITIES,2,CITY_SIZE);
CITY_SIZE = 52;
CITIES = CITIES';
CITIES = CITIES(1:CITY_SIZE,:)
function y = euc_2d(c1, c2)
x1 = c1(1) - c2(1);
x1 = x1 * x1;
x2 = c1(2) - c2(2);
x2 = x2 * x2;
y = round(sqrt( x1 + x2));
endfunction
function distance = cost(perm, cities)
distance = 0;
c1 = [1:CITY_SIZE];
c2 = [2:CITY_SIZE,1];
for i = 1:CITY_SIZE
distance = distance + euc_2d(cities(perm(c1(i)),:), cities(perm(c2(i)),:));
end
endfunction
function perm = random_permutation()
perm = [1:CITY_SIZE];
for i = 1:CITY_SIZE
r = rand(1) * (CITY_SIZE - i) + i;
r = round(r);
if r == 0 then
r = 1;
end
tp = perm(i);
perm(i) = perm(r);
perm(r) = tp;
end
endfunction
function perm = stochastic_two_opt(parent)
perm = parent;
c = round(rand(1,2) * (CITY_SIZE - 2) + 2);
while c(1) == c(2)
c = round(rand(1,2) * (CITY_SIZE - 2) + 2);
end
c1 = c(1);
c2 = c(2);
if c2 < c1 then
tp = c2;
c2 = c1;
c1 = tp;
end
perm(c1:c2) = perm(c2:-1:c1);
//p = perm(c1);
//perm(c1) = perm(c2);
//perm(c2) = tp;
endfunction
function candidate = create_neighbor(current, cities)
candidate = current;
candidate = stochastic_two_opt(candidate);
endfunction
function is_accept = should_accept(candidate, current, temp, cities)
if cost(candidate, cities) <= cost(current, cities) then
is_accept = 1;
return;
end
is_accept = exp( (cost(current, cities) -cost(candidate, cities)) / temp) > rand(1);
endfunction
function best = search(cities, max_iter, max_temp, temp_change)
current = random_permutation();
cost_ = cost(current, cities);
temp = max_temp;
best = current;
for i = 1:max_iter
candidate = create_neighbor(current, cities);
temp = temp * temp_change;
if should_accept(candidate, current, temp, cities) == 1 then
current = candidate;
end
if cost( candidate, cities) < cost(best, cities) then
best = candidate;
disp([cost( candidate, cities),i]);
end
end
endfunction
max_iter = 10000;
max_temp = 100000;
temp_change = 0.98;
cities = CITIES;
best = search(cities, max_iter, max_temp, temp_change);
cost_ = cost(best, cities);
disp(cost_)
plot(cities( [best,best(1)] ,1), cities([best,best(1)],2), '-o');