Pacman-N-queen

文档

代码及文档:通过网盘分享的文件:code
链接: https://pan.baidu.com/s/1Rgo9ynnEqjZsSP2-6TyS8Q?pwd=n99p 提取码: n99p
在这里插入图片描述
在这里插入图片描述


补充核心代码

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述


核心代码内容:

genetic_algorithm,py

# -*- coding: utf-8 -*-
"""
Created on Sun Jul 25 10:01:26 2021@author: zyw
"""import numpy as np
import matplotlib.pyplot as pltfrom queen import Queendef select(C):'''This method is used to select two indices of individuals for crossoverParameters----------C : list of cost of indivduals.Returns-------two indices'''n = len(C)p = []for idx in range(2):i = np.random.randint(n)j = np.random.randint(n)if C[i] < C[j] and np.random.rand() < 0.9:p.append(i)else:p.append(j)return p[0], p[1]def crossover(p1, p2):n = len(p1)pos = np.random.randint(n)c1 = p1.copy()for i in range(pos, n):c1[i] = p2[i]c2 = p2.copy()for i in range(pos, n):c2[i] = p1[i]return c1, c2def mutation(x):'''find a new solution randomly'''y = x.copy()i = np.random.randint(y.size)y[i] = (y[i] + 1 + np.random.randint(y.size-1)) % y.sizereturn ydef replacement(P, C, OFF, NC):'''replacement for genetic algorithm, current P and offspring OFF compete for surviving Parameters----------P : list of current population.C : costs of current individualsOFF : list of offspringNC : cost of offspringReturns-------none'''for i in range(len(C)):if NC[i] < C[i] or (np.random.rand() < 0.1 and C[i] != 0):P[i] = OFF[i]C[i] = NC[i]def genetic_algorithm(f, n, N = 20, M = 1000, cxProb = 1.0, mtProb = 1.0):'''This is a toy genetic algorithm n is number of queenf is cost functionN is population sizeM is iteration timescxProb is crossover probabilitymtProb is mutation probability'''X = [Queen.init_solution(n) for i in range(N)]C = [f(x) for x in X]costs = np.zeros([M,2])## add your code here -------------------------------------------------for generation in range(M):# Select parentsp1, p2 = select(C)# Perform crossoverc1, c2 = crossover(X[p1], X[p2]) if np.random.rand() < cxProb else X[p1], X[p2]# Perform mutationc1 = mutation(c1) if np.random.rand() < mtProb else c1c2 = mutation(c2) if np.random.rand() < mtProb else c2# Evaluate offspringC1 = f(c1)C2 = f(c2)# Replace populationreplacement(X, C, [c1, c2], [C1, C2])# Track costscosts[generation, 0] = min(C)costs[generation, 1] = max(C)## end your code ------------------------------------------------------np.savetxt("convergence.csv", costs, fmt="%d", delimiter=",")y = np.array(range(M))plt.plot(y, costs, linewidth=2)plt.show()return X[C.index(min(C))], min(C)if __name__=="__main__":num = 16best, best_value = genetic_algorithm(Queen.eval, num)print(best, best_value)Queen.display(best)

local_search.py

# -*- coding: utf-8 -*-
"""
Created on Sun Jul 25 10:01:26 2021@author: zyw
"""import numpy as np
import matplotlib.pyplot as pltfrom queen import Queendef neighbor(x):'''find a new solution randomly'''y = x.copy()i = np.random.randint(y.size)y[i] = (y[i] + 1 + np.random.randint(y.size-1)) % y.sizereturn ydef random_search(f, x, iteration_times=1000):min_value = f(x)min_x = x.copy()value = min_valuecosts = np.zeros([iteration_times,2])for i in range(iteration_times):for j in range(len(x)):x = neighbor(x)value = f(x)if value < min_value:min_value = valuemin_x = x.copy()costs[i][0] = valuecosts[i][1] = min_valuenp.savetxt("convergence.csv", costs, fmt="%d", delimiter=",")y = np.array(range(iteration_times))plt.plot(y, costs, linewidth=2)plt.show()return min_x, min_valuedef greedy_search(f, x, iteration_times=1000):value = f(x)costs = np.zeros([iteration_times,1])for i in range(iteration_times):for j in range(len(x)):nx = neighbor(x)nvalue = f(nx)if nvalue < value:value = nvaluex = nxcosts[i][0] = valuenp.savetxt("convergence.csv", costs, fmt="%d", delimiter=",")y = np.array(range(iteration_times))plt.plot(y, costs, linewidth=2)plt.show()return x, valuedef hill_climbing(f, x):value = f(x)improved = True## add your code here -------------------------------------------------while improved:improved = Falsefor i in range(len(x)):nx = neighbor(x)nvalue = f(nx)if nvalue < value:value = nvaluex = nximproved = True## end your code ------------------------------------------------------return x, valuedef simulated_annealing(f, x, iteration_times=500, t0=100, alpha=0.9):'''This is a toy simulated annealing algorithm '''min_value = f(x)min_x = x.copy()value = min_valuet = t0costs = np.zeros([iteration_times,2])## add your code here -------------------------------------------------for i in range(iteration_times):for j in range(len(x)):nx = neighbor(x)nvalue = f(nx)delta = nvalue - valueif delta < 0 or np.random.rand() < np.exp(-delta / t):x = nxvalue = nvalueif value < min_value:min_value = valuemin_x = x.copy()t *= alpha  # Decrease temperature## end your code ------------------------------------------------------np.savetxt("convergence.csv", costs, fmt="%d", delimiter=",")y = np.array(range(iteration_times))plt.plot(y, costs, linewidth=2)plt.show()return min_x, min_valueif __name__=="__main__":num = 8x = Queen.init_solution(num)#best, best_value = random_search(Queen.eval, x)best, best_value = greedy_search(Queen.eval, x)#best, best_value = hill_climbing(Queen.eval, x)#best, best_value = simulated_annealing(Queen.eval, x)print(best_value, best)Queen.display(best)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/903139.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

常用的多传感器数据融合方法

1. 概述 根据具体需求&#xff08;实时性、计算资源、噪声特性&#xff09;选择合适的方法&#xff0c;实际应用中常结合多种方法&#xff08;如UKF与神经网络结合&#xff09;。 传统方法 &#xff08;KF/EKF/UKF/PF&#xff09;依赖数学模型&#xff0c;适合动态系统&#…

简单几步,开启 Intel VT-x 让电脑“解开CPU封印”

#vmware #虚拟机 #cpu虚拟化 # Intel VT-x 前言 你是不是也遇到过这种情况&#xff1a;在尝试运行虚拟机&#xff08;VM&#xff09;、安卓模拟器&#xff0c;或者使用 Windows 沙盒、WSL2 等功能时&#xff0c;遇到了类似“此主机支持 Intel VT-x&#xff0c;但 Intel VT-x …

Go语言--语法基础4--基本数据类型--字符串类型

在 Go 语言中&#xff0c;字符串也是一种基本类型。相比之下&#xff0c; C/C 语言中并不存在原 生的字符串类型&#xff0c; 通常使用字符数组来表示&#xff0c;并以字符指针来传递。 Go 语言中字符串的声明和初始化非常简单&#xff0c;举例如下&#xff1a; var str st…

QT中的事件及其属性

Qt中的事件是对操作系统提供的事件机制进行封装&#xff0c;Qt中的信号槽就是对事件机制的进一步封装 但是特殊情况下&#xff0c;如对于没有提供信号的用户操作&#xff0c;就需要通过重写事件处理的形式&#xff0c;来手动处理事件的响应逻辑 常见的Qt事件&#xff1a; 常见事…

socket套接字-UDP(中)

socket套接字-UDP&#xff08;上&#xff09;https://blog.csdn.net/Small_entreprene/article/details/147465441?fromshareblogdetail&sharetypeblogdetail&sharerId147465441&sharereferPC&sharesourceSmall_entreprene&sharefromfrom_link UDP服务器…

C++入门小馆: STL 之queue和stack

嘿&#xff0c;各位技术潮人&#xff01;好久不见甚是想念。生活就像一场奇妙冒险&#xff0c;而编程就是那把超酷的万能钥匙。此刻&#xff0c;阳光洒在键盘上&#xff0c;灵感在指尖跳跃&#xff0c;让我们抛开一切束缚&#xff0c;给平淡日子加点料&#xff0c;注入满满的pa…

ALTER TABLE 删除DROP表列的报错: 因为有一个或多个对象访问此列

目录 1.问题 2.解决办法 1.问题 删除某个列名的时候&#xff0c;提示错误因为有一个或多个对象访问此列 2.解决办法 2.1 添加或删除表新列名 将表中的字段设置Default 或 NOT NULL 都会给该字段添加约束&#xff0c;增加了这些约束后&#xff0c;再SQL脚本修改类型、删除会发生…

python源码打包为可执行的exe文件

文章目录 简单的方式&#xff08;PyInstaller&#xff09;特点步骤安装 PyInstaller打包脚本得到.exe文件 简单的方式&#xff08;PyInstaller&#xff09; 特点 支持 Python 3.6打包为单文件&#xff08;–onefile&#xff09;或文件夹形式自动处理依赖项 步骤 安装 PyIns…

【2025最近Java面试八股】Spring中循环依赖的问题?怎么解决的?

1. 什么是循环依赖&#xff1f; 在Spring框架中&#xff0c;循环依赖是指两个或多个bean之间相互依赖&#xff0c;形成了一个循环引用的情况。如果不加以处理&#xff0c;这种情况会导致应用程序启动失败。导致 Spring 容器无法完成依赖注入。 例如&#xff1a; Service publi…

JimuBI 积木报表 v1.9.5发布,大屏和仪表盘,免费数据可视化

项目介绍 JimuBI (积木报表BI) 是一款免费的数据可视化产品&#xff0c;含大屏和仪表盘、门户、移动图表&#xff0c;像搭建积木一样完全在线设计&#xff01; 大屏采用类word风格&#xff0c;可以随意拖动组件&#xff0c;想怎么设计怎么设计&#xff0c;可以像百度和阿里一样…

云原生课程-Docker

一次镜像&#xff0c;到处运行。 1. Docker详解&#xff1a; 1.1 Docker简介&#xff1a; Docker是一个开源的容器化平台&#xff0c;可以帮助开发者将应用程序和其依赖的环境打包成一个可移植的&#xff0c;可部署的容器。 docker daemon:是一个运行在宿主机&#xff08;DO…

HikariCP 6.3.0 完整配置与 Keepalive 优化指南

HikariCP 6.3.0 完整配置与 Keepalive 优化指南 HikariCP 是一个高性能、轻量级的 JDBC 连接池框架&#xff0c;广泛应用于 Java 应用&#xff0c;尤其是 Spring Boot 项目。本文档基于 HikariCP 6.3.0 版本&#xff0c;详细介绍其功能、配置参数、Keepalive 机制以及优化建议…

基于springboot+vue的摄影师分享交流社区的设计与实现

开发语言&#xff1a;Java框架&#xff1a;springbootJDK版本&#xff1a;JDK1.8服务器&#xff1a;tomcat7数据库&#xff1a;mysql 5.7&#xff08;一定要5.7版本&#xff09;数据库工具&#xff1a;Navicat11开发软件&#xff1a;eclipse/myeclipse/ideaMaven包&#xff1a;…

ComfyUI for Windwos与 Stable Diffusion WebUI 模型共享修复

#工作记录 虽然在安装ComfyUI for Windwos时已经配置过extra_model_paths.yaml 文件&#xff0c;但升级ComfyUI for Windwos到最新版本后发现原先的模型配置失效了&#xff0c;排查后发现&#xff0c;原来是 extra_model_paths.yaml 文件在新版本中被移动到了C盘目录下&#x…

【最新版】沃德代驾源码全开源+前端uniapp

一.系统介绍 基于ThinkPHPUniapp开发的代驾软件。系统源码全开源&#xff0c;代驾软件的主要功能包括预约代驾、在线抢单、一键定位、在线支付、车主登记和代驾司机实名登记等‌。用户可以通过小程序预约代驾服务&#xff0c;系统会估算代驾价格并推送附近代驾司机供用户选择&…

react的 Fiber 节点的链表存储

在React Fiber架构中&#xff0c;Fiber节点的链表存储是一种重要的数据结构组织方式&#xff0c;用于管理和遍历Fiber节点。以下是关于Fiber节点链表存储的详细介绍&#xff1a; 链表结构 单链表&#xff1a;React Fiber节点通过next指针形成单链表结构。每个Fiber节点都有一…

Kafka + Kafka-UI

文章目录 前言&#x1f433; 一、使用纯 Kafka Kafka-UI &#xff08;无 Zookeeper&#xff09;Docker 配置&#x1f680; 启动步骤✅ 服务启动后地址&#x1f525; 注意事项&#xff08;使用 Kraft&#xff09;✅ NestJS Kafka 连接不变&#x1f9e0; 额外补充&#x1f4e6; …

AI声像融合守护幼儿安全——打骂/异常声音报警系统的智慧防护

幼儿园是孩子们快乐成长的摇篮&#xff0c;但打骂、哭闹或尖叫等异常事件可能打破这份宁静&#xff0c;威胁幼儿的身心安全。打骂/异常声音报警系统&#xff0c;依托尖端的AI声像融合技术&#xff0c;结合语音识别、情绪分析与视频行为检测&#xff0c;为幼儿园筑起一道智能安全…

Qt网络数据解析方法总结

在Qt中解析网络数据通常涉及接收原始字节流&#xff0c;并将其转换为有意义的应用层数据。以下是详细步骤和示例&#xff1a; 1. 网络数据接收 使用QTcpSocket或QUdpSocket接收数据&#xff0c;通过readyRead()信号触发读取&#xff1a; // 创建TCP Socket并连接信号 QTcpSo…

unity编辑器的json验证及格式化

UNITY编辑器的json格式化和验证工具资源-CSDN文库https://download.csdn.net/download/qq_38655924/90676188?spm1001.2014.3001.5501 反复去别的网站验证json太麻烦了 用这个工具能方便点 # Unity JSON工具 这是一个Unity编辑器扩展&#xff0c;用于验证、格式化和压缩JSO…