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.pswp.cn/news/903139.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/903139.shtml
英文地址,請注明出處:http://en.pswp.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…