python遗传算法八皇后_Python利用遗传算法解决八皇后问题

该博客通过Python实现遗传算法来解决经典的八皇后问题。首先初始化棋盘状态,然后选择适应度高的父代进行交叉和变异操作。通过不断迭代,当找到一个没有冲突的解决方案时,展示解并终止循环。最后,使用matplotlib绘制了八皇后的位置。
摘要由CSDN通过智能技术生成

import random

import matplotlib.pyplot as plt

a=[]

b=[]

c=[]

d=[]

def initState(a):

while len(a)<8:

a.append(random.randint(1,8))

return a

def chooseParent(a,b,c,d):

parent=[]

stack=[]

stack.append(a)

stack.append(b)

stack.append(c)

stack.append(d)

fitnessValue=fitnessFunc(stack)

sort=sorted(fitnessValue.items(),key=lambda e:e[1],reverse=True)

if sort[0][0]=='a':

firstFather=a

elif sort[0][0]=='b':

firstFather=b

elif sort[0][0]=='c':

firstFather=c

else:firstFather=d

parent.append(firstFather)

if sort[1][0]=='a':

firstMother=a

elif sort[1][0]=='b':

firstMother=b

elif sort[1][0]=='c':

firstMother=c

else:firstMother=d

parent.append(firstMother)

secondFather=firstFather

parent.append(secondFather)

if sort[2][0]=='a':

secondMother=a

elif sort[2][0]=='b':

secondMother=b

elif sort[2][0]=='c':

secondMother=c

else:secondMother=d

parent.append(secondMother)

return parent

def fitnessFunc(myList):

fitnessIndex=[28,28,28,28]

for c in range(0,4):

for i in range(0,7):

for n in range(i+1,8):

if myList[c][i]==myList[c][n]:

fitnessIndex[c]-=1

if myList[c][i]+n-i==myList[c][n] or myList[c][i]-n+i==myList[c][n]:

fitnessIndex[c]-=1

fitnessDict={'a':fitnessIndex[0],'b':fitnessIndex[1],'c':fitnessIndex[2],'d':fitnessIndex[3]}

return fitnessDict

def crossOver(myList):

newList=[]

crossPoint=random.randint(1,7)

ff=myList[0]

fm=myList[1]

sf=myList[2]

sm=myList[3]

fchild1=ff[0:crossPoint]

fchild1.extend(fm[crossPoint:])

fchild2=fm[0:crossPoint]

fchild2.extend(ff[crossPoint:])

schild1=sf[0:crossPoint]

schild1.extend(sm[crossPoint:])

schild2=sm[0:crossPoint]

schild2.extend(sf[crossPoint:])

newList.append(fchild1)

newList.append(fchild2)

newList.append(schild1)

newList.append(schild2)

return newList

def mutationPoint():

mPoint=random.randint(0,8)

return mPoint

def mutationNumber():

mNumber=random.randint(1,8)

return mNumber

def mutation(myList):

childMutationList=[]

fc1_mPoint=mutationPoint()

fc1_mNumber=mutationNumber()

fchild1=myList[0]

if fc1_mPoint==0:

fchild1_m=fchild1

else:

fchild1_m=fchild1

fchild1_m[fc1_mPoint-1]=fc1_mNumber

fc2_mPoint=mutationPoint()

fc2_mNumber=mutationNumber()

fchild2=myList[1]

if fc2_mPoint==0:

fchild2_m=fchild2

else:

fchild2_m=fchild2

fchild2_m[fc2_mPoint-1]=fc2_mNumber

sc1_mPoint=mutationPoint()

sc1_mNumber=mutationNumber()

schild1=myList[2]

if sc1_mPoint==0:

schild1_m=schild1

else:

schild1_m=schild1

schild1_m[sc1_mPoint-1]=sc1_mNumber

sc2_mPoint=mutationPoint()

sc2_mNumber=mutationNumber()

schild2=myList[3]

if sc2_mPoint==0:

schild2_m=schild2

else:

schild2_m=schild2

schild2_m[sc2_mPoint-1]=sc2_mNumber

childMutationList.append(fchild1_m)

childMutationList.append(fchild2_m)

childMutationList.append(schild1_m)

childMutationList.append(schild2_m)

return childMutationList

print(initState(a))

print(initState(b))

print(initState(c))

print(initState(d))

parent=chooseParent(a,b,c,d)

# print(parent)

answer=[]

asumeCount=0

while(True):

crossParent=crossOver(parent)

mutationParent=mutation(crossParent)

newFitDict=fitnessFunc(mutationParent)

asumeCount+=1

if newFitDict['a']==28 or newFitDict['b']==28 or newFitDict['c']==28 or newFitDict['d']==28:

if newFitDict['a']==28:

answer.append(mutationParent[0])

if newFitDict['b']==28:

answer.append(mutationParent[1])

if newFitDict['c']==28:

answer.append(mutationParent[2])

if newFitDict['d']==28:

answer.append(mutationParent[3])

print("I find it! The answer is {0}".format(answer))

print("I did {0} cycle to find it".format(asumeCount))

for i in answer:

pointA=i.index(1)+1

pointB=i.index(2)+1

pointC=i.index(3)+1

pointD=i.index(4)+1

pointE=i.index(5)+1

pointF=i.index(6)+1

pointG=i.index(7)+1

pointH=i.index(8)+1

x=[1,2,3,4,5,6,7,8]

y=[pointA,pointB,pointC,pointD,pointE,pointF,pointG,pointH]

plt.axis([0,9,0,9])

plt.plot(x,y, '*')

plt.show()

break

else:parent=mutationParent

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
八皇后问题是一个经典的问题,旨在寻找一个方法,在棋盘上放置8个皇后,使得没有一个皇后能够攻击到另外一个。这个问题可以用遗传算法解决遗传算法是一种优化算法,它模仿自然选择和遗传学原理。该算法从一个初始种群开始,每一代通过交叉、变异、选择等操作来产生下一代种群,最终得到一个优化结果。 在使用遗传算法解决八皇后问题时,首先需要定义一个个体的编码方式,例如使用一个长度为8的序列来表示每个皇后在每一列的位置。然后,需要定义适应度函数来评估每个个体的优劣程度。对于八皇后问题,适应度函数可以定义为:对于每个皇后,如果在同一行或同一对角线上有另一个皇后,则适应度函数为0;否则为1。最后,通过遗传算法迭代多次,找到一个适应度函数最大的个体作为最优解。 以下是使用Python实现八皇后问题遗传算法的一些代码示例: ``` import random # 随机生成初始种群 def generate_population(size): population = [] for i in range(size): individual = [] for j in range(8): individual.append(random.randint(0, 7)) population.append(individual) return population # 计算适应度函数 def fitness(individual): fitness = 0 for i in range(8): for j in range(i+1, 8): if individual[i] == individual[j] or abs(individual[i] - individual[j]) == j - i: fitness += 1 return fitness # 选择操作 def selection(population): fitnesses = [fitness(individual) for individual in population] max_fitness = max(fitnesses) max_fitness_index = fitnesses.index(max_fitness) return population[max_fitness_index] # 交叉操作 def crossover(parent1, parent2): crossover_point = random.randint(0, 7) child = parent1[:crossover_point] + parent2[crossover_point:] return child # 变异操作 def mutation(individual): mutation_point = random.randint(0, 7) new_value = random.randint(0, 7) individual[mutation_point] = new_value return individual # 遗传算法主程序 def genetic_algorithm(): population_size = 100 generations = 1000 population = generate_population(population_size) for i in range(generations): new_population = [] for j in range(population_size): parent1 = selection(population) parent2 = selection(population) child = crossover(parent1, parent2) if random.random() < 0.1: child = mutation(child) new_population.append(child) population = new_population best_individual = selection(population) return best_individual best_individual = genetic_algorithm() print(best_individual) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值