c语言推销员旅行问题遗传算法,基于遗传算法的旅行推销员

我试图用python和遗传算法来可视化和解决旅行销售人员的问题,我在youtube上关注Daniel Shiffman的一个编码挑战视频我不知道是否允许我在这里放一个链接,但这里是链接(https://www.youtube.com/watch?v=M3KTWnTrU_c&list=PLRqwX-V7Uu6ZiZxtDDRCi6uhfTH4FilpH&index=42)

所以问题是,我的遗传算法没有进化。它仅仅停留在第一代上。我想我无法写出创建下一代的代码,因为我缺乏python知识,下面是代码:import pygame

import random

import numpy as np

import sys

size=width,height=500,500

bgColor = (0,0,0)

screen = pygame.display.set_mode(size)

vertexArray = []

fitness = []

population = []

pygame.display.set_caption("Finding the Shortest path with Genetich Algorithm")

bestEver=[]

bestDistance = 999999

def shuffle(vertexArray):

np.random.shuffle(vertexArray)

def swap(a,i,j):

temp = a[i]

a[i]=a[j]

a[j]=temp

class Vertex:

def __init__(self,x,y):

self.color = (255,255,255)

self.x = x

self.y = y

def display(self):

pygame.draw.circle(screen,self.color,(self.x,self.y),4,4)

def getPosition(self):

return [self.x,self.y]

def __str__(self):

return str(self.x+", "+self.y)

def createVertexes(numOfVertexes):

for i in range(numOfVertexes):

vertexArray.append(Vertex(random.randint(0,width),random.randint(0,height)))

createVertexes(8)

def createPopulation():

for i in range(300):

population.append(vertexArray[:])

for j in range(100):

shuffle(population[i])

createPopulation()

def drawLines(vertexArray,color):

for i in range(vertexArray.__len__()-1):

pygame.draw.line(screen,color,vertexArray[i].getPosition(),vertexArray[i+1].getPosition(),1)

def calculateDistance(vertexArray):

dist = 0

for i in range(vertexArray.__len__()-1):

dist += np.linalg.norm(np.asarray(vertexArray[i+1].getPosition())-np.asarray(vertexArray[i].getPosition()))

return dist

def displayVertexes(vertexArray):

for i in range(vertexArray.__len__()):

vertexArray[i].display()

def calculateFitness():

global bestDistance

global bestEver

for i in range(population.__len__()-1):

d = calculateDistance(population[i])

if d

bestDistance = d

bestEver = population[i][:]

fitness.append(1/d)

def getProbability(fitness,population):

first = 0

sum = 0

for i in range(fitness.__len__() - 1):

sum += fitness[i]

r = random.uniform(0, sum)

for i in range(fitness.__len__() - 1):

if r<=fitness[i] and r>=first:

return population[i]

first = fitness[i]

return population[random.randint(0,2)]

def pickOne(population,fitness):

return getProbability(fitness,population)

def mutate(order):

indexA = random.randint(0,order.__len__()-1)

indexB = random.randint(0,order.__len__()-1)

swap(order,indexA,indexB)

def nextGeneration():

global population

newPopulation=[]

for i in range(population.__len__()-1):

order = pickOne(population,fitness)

mutate(order)

newPopulation.append(order)

population = newPopulation

while True:

for event in pygame.event.get():

if event.type == pygame.QUIT:

sys.exit()

screen.fill(bgColor)

displayVertexes(vertexArray)

calculateFitness()

print(fitness[2])

nextGeneration()

drawLines(bestEver,(255, 0, 0))

pygame.display.flip()

你可能感兴趣的:(c语言推销员旅行问题遗传算法)