#引入相应的库函数
using Plots
using Random: shuffle
#处理城市坐标
Path =[[41,94],[37,84],[54,67],[25,62],[7,64],[2,99],[68,58],[71,44],[54,62],[83,69],[64,60],[18,54],[22,60],[83,46],[91,38],[25,38],[24,42],[58,69],[71,71],[74,78],[87,76],[13,40],[82,7],[62,32],[58,35],[45,21],[41,26],[44,35],[4,50]]#设置循环几轮
num =100000#画出城市所在的散点图
x =[i[1]for i in Path]
y =[i[2]for i in Path]
plot(x,y, seriestype=:scatter,label ="city_path")#创建祖先
function create_ancestor(num)
ancestor =[]
standard =[i for i in1:length(Path)]for i in1:num
push!(ancestor,shuffle(standard))
end
return ancestor
end
#计算距离函数
function calculate_rem(a,b)
x1 = a[1]
y1 = a[2]
x2 = b[1]
y2 = b[2]return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))
end
#计算成绩函数
function calculate(player,Path)
rem =[]for i in player
temp =0for j in1:length(Path)-1
temp = temp+calculate_rem(Path[i[j]],Path[i[j+1]])
end
append!(rem,temp)
end
return rem
end
#淘汰成绩最不理想的一半
function disuse(player,score)for i in1:length(player)/2
temp = findmax(score)[2]
deleteat!(score,temp)
deleteat!(player,temp)
end
return player
end
#剩下的变异
function mutations(player,degree)
temp =[]for i in player
append!(temp,[i])
des = deepcopy(i)for j in1:degree
a = rand(1:length(i))
b = rand(1:length(i))
t = des[a]
des[a]= des[b]
des[b]= t
end
append!(temp,[des])
end
return temp
end
#主函数
player = create_ancestor(10000)for i in1:num
score = calculate(player,Path)
player = disuse(player,score)
player = mutations(player,1)
end
score = calculate(player,Path)
ind = findmin(score)[2]
println(score[ind])
println(player[ind])#画出多次选择后最优的路线
x =[Path[i][1]for i in player[ind]]
y =[Path[i][2]for i in player[ind]]
plot(x,y,label ="city_path",marker=(:circle,5))