通用算法,用于带数字[闭]的n个皇后问题

问题描述 投票:-2回答:1

[你好,有人可以解决我的问题,我无法理解8或4个皇后的通用算法的整个代码,我知道什么是通用算法,但是特定功能及其对特定功能的作用可以帮助或告诉我一个网站可以给出解释

因为此代码包含没有特定编号的数字,所以要依赖它

import random
import copy
import sys

def random_selection1(population, fitness_fn, goal_fit):
    selection = None
    current_amount = 0
    fitness_total = []
    selection = []
    for i in range(len(population)):
        current_amount += fitness_fn(population[i], goal_fit)
        fitness_total.append(current_amount)
    prob = random.uniform(0, fitness_total[-1])
    print(prob)
    print(fitness_total, fitness_total[-1], max(fitness_total))
    for i in range(len(population)):
        if fitness_total[i] > prob:
            return population[i]


def random_selection(population, fitness_fn, goal_fit):
        current_amount = 0
        total = 0
        fitness = []
        fitness_total = []
        random.shuffle(population)
        for i in range(len(population)):
                current_amount = fitness_fn(population[i], goal_fit)
                fitness.append(current_amount)
        total = sum(fitness)
        for i in range(len(fitness)):
                fitness_total.append(fitness[i]/total)

        sorted_fitness = copy.deepcopy(fitness_total)
        sorted_fitness.sort()
        mini = sorted_fitness[(int)(0.2*len(fitness))]
        #print(mini, sorted_fitness[len(fitness)-1], max(fitness_total)) 
        prob = random.uniform(mini, max(fitness_total))
        #print(prob)
        #print(fitness_total, fitness_total[-1], max(fitness_total))
        for i in range(len(population)):
                if fitness_total[i] > prob:
                        return population[i]
        return population[0]


def mutation(child):
        i = random.randint(0, len(child)-1)
        j = random.randint(0, len(child)-1)
        child[i] = j
        return child


def reproduce(x, y):
        n = len(x)-1
        crossover_point = random.randint(1, n)
        #print(crossover_point)
        #print(x[0:crossover_point])
        #print(y[crossover_point:n+1])
        child = x[0:crossover_point] + y[crossover_point:n+1]
        return child


def reproduce1(x):
    return switch(2, x)


def compute_goal_fit(n):
    goal_fit = 0
    for i in range(n):
        goal_fit += i
    return goal_fit


def switch(n, target):
    for i in range(n):
        j = random.randint(0, len(target)-1)
        k = random.randint(0, len(target)-1)
        target[j], target[k] = target[k], target[j]
    return target


def gen_alg(population, fitness, goal_fit, nmax):
    n = nmax

    print("\nrunning...") 
    while n > 0: 
        new_population = []
        for i in range(len(population)):
            x = random_selection(population, fitness_fn, goal_fit)
            y = random_selection(population, fitness_fn, goal_fit)
            #print('x: ', x, fitness(x, goal_fit))
            #print('y: ', y, fitness(y, goal_fit))
            child = reproduce(x, y)
            #print('child: ', child)
            if random.uniform(0,1) < 0.8:
                child = mutation(child)
            #print('child: ', child, fitness(child, goal_fit))
            if fitness(child, goal_fit) >= goal_fit:
                print("...done. \n\nresult ", child," found in ", nmax-n, " generations.\n")
                return child    
            new_population.append(child)
        population = new_population 
        n -= 1

    print("\nno solution found in ", nmax, " generations, try again.\n")
    return None



def fitness_fn(individual, goal_fit):
    fitness_value = goal_fit
    for i in range(len(individual)):
        j = 1
        while j < len(individual)-i:
            if (individual[i] == individual[i+j]) or (individual[i] == individual[i+j]+j) or (individual[i] == individual[i+j]-j):
                fitness_value -= 1
            j += 1
    return fitness_value



#def print_population():

#---------------------------------------main---------------------------------------

n = 8
population = []
base = range(n)
nmax = 100000
flag = False
k=-1
for i in range(8):
    population.append(switch(5, list(base)))

goal_fit = compute_goal_fit(len(random.choice(population)))

print("\nproblem dimension: ", n, "x", n) #len(random.choice(population)
print("population size: ", len(population)) 
print("max generations: ", nmax)
print("Goal fit: ", goal_fit)
for i in range(8):
        fn = fitness_fn(population[i], goal_fit)
        print(population[i], fn)
        if fn >= goal_fit:
                flag = True
                k = i

if flag == True:
        print("...done. \n\nresult ", population[k]," found in 0 generations.\n")
        sys.exit()

gen_alg(population, fitness_fn, goal_fit, nmax)
python algorithm generic-programming
1个回答
-1
投票
欢迎使用Stack溢出。

遗传算法与新的适应度函数一起用作元启发式算法。 N皇后问题的目的是将N个皇后放置在N x N的棋盘上,以确保没有一个皇后与其他皇后发生冲突。详细描述了染色体代表和遗传操作,如突变和交叉。

请通过这些链接

https://aljrico.github.io/blog/genetic-algorithms/https://www.researchgate.net/publication/281953623_Solving_N_Queen_Problem_using_Genetic_Algorithm

可能对您有帮助😊

© www.soinside.com 2019 - 2024. All rights reserved.