OptaPlanner筆記6 N皇后

N 個皇后

問題描述

將n個皇后放在n大小的棋盤上,沒有兩個皇后可以互相攻擊。 最常見的 n 個皇后謎題是八個皇后謎題,n = 8:
在這里插入圖片描述
約束:

  • 使用 n 列和 n 行的棋盤。
  • 在棋盤上放置n個皇后。
  • 沒有兩個女王可以互相攻擊。女王可以攻擊同一水平線、垂直線或對角線上的任何其他女王。

求解結果(time limit 5s)

在這里插入圖片描述

問題大小

n搜索空間
4256
810^7
1610^19
3210^48
6410^115
25610^616

域模型

@Data
@AllArgsConstructor
public class Column {private int index;
}
@Data
@AllArgsConstructor
public class Row {private int index;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@PlanningEntity
public class Queen {@PlanningIdprivate Integer id;@PlanningVariableprivate Column column;@PlanningVariableprivate Row row;// 升序對角線索引(左上到右下)public int getAscendingDiagonalIndex() {return column.getIndex() + row.getIndex();}// 降序對角線索引(左下到右上)public int getDescendingDiagonalIndex() {return column.getIndex() - row.getIndex();}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@PlanningSolution
public class NQueen {@ValueRangeProvider@ProblemFactCollectionPropertyprivate List<Column> columnList;@ValueRangeProvider@ProblemFactCollectionPropertyprivate List<Row> rowList;@PlanningEntityCollectionPropertyprivate List<Queen> queenList;@PlanningScoreprivate HardSoftScore score;
}

例如:
在這里插入圖片描述

QueenColumnRowAscendingDiagonalIndexDescendingDiagonalIndex
A1011 (**)-1
B010 (*)1 (**)1
C22240
D030 (*)33

(*)(**)的皇后可以互相攻擊

求解器(約束提供者)

public class NQueenConstraintProvider implements ConstraintProvider {@Overridepublic Constraint[] defineConstraints(ConstraintFactory constraintFactory) {return new Constraint[]{// 列沖突columnConflict(constraintFactory),// 行沖突rowConflict(constraintFactory),// 升序對角線沖突ascendingDiagonalIndexConflict(constraintFactory),// 降序對角線沖突descendingDiagonalIndexConflict(constraintFactory),};}public Constraint columnConflict(ConstraintFactory constraintFactory) {return constraintFactory.forEach(Queen.class).join(Queen.class,Joiners.equal(Queen::getColumn),Joiners.lessThan(Queen::getId)).penalize(HardSoftScore.ONE_HARD).asConstraint("Column conflict");}public Constraint rowConflict(ConstraintFactory constraintFactory) {return constraintFactory.forEach(Queen.class).join(Queen.class,Joiners.equal(Queen::getRow),Joiners.lessThan(Queen::getId)).penalize(HardSoftScore.ONE_HARD).asConstraint("Row conflict");}public Constraint ascendingDiagonalIndexConflict(ConstraintFactory constraintFactory) {return constraintFactory.forEach(Queen.class).join(Queen.class,Joiners.equal(Queen::getAscendingDiagonalIndex),Joiners.lessThan(Queen::getId)).penalize(HardSoftScore.ONE_HARD).asConstraint("AscendingDiagonalIndex conflict");}public Constraint descendingDiagonalIndexConflict(ConstraintFactory constraintFactory) {return constraintFactory.forEach(Queen.class).join(Queen.class,Joiners.equal(Queen::getDescendingDiagonalIndex),Joiners.lessThan(Queen::getId)).penalize(HardSoftScore.ONE_HARD).asConstraint("DescendingDiagonalIndex conflict");}
}

應用

public class NQueenApp {public static void main(String[] args) {SolverFactory<NQueen> solverFactory = SolverFactory.create(new SolverConfig().withSolutionClass(NQueen.class).withEntityClasses(Queen.class).withConstraintProviderClass(NQueenConstraintProvider.class).withTerminationSpentLimit(Duration.ofSeconds(5)));NQueen problem = generateDemoData();Solver<NQueen> solver = solverFactory.buildSolver();NQueen solution = solver.solve(problem);printTimetable(solution);}public static NQueen generateDemoData() {List<Column> columnList = new ArrayList<>();List<Row> rowList = new ArrayList<>();List<Queen> queenList = new ArrayList<>();for (int i = 0; i < 8; i++) {columnList.add(new Column(i));rowList.add(new Row(i));queenList.add(new Queen(i, null, null));}return new NQueen(columnList, rowList, queenList, null);}private static void printTimetable(NQueen nQueen) {System.out.println("");List<Column> columnList = nQueen.getColumnList();List<Row> rowList = nQueen.getRowList();List<Queen> queenList = nQueen.getQueenList();Map<Column, Map<Row, List<Queen>>> queenMap = queenList.stream().filter(queen -> queen.getColumn() != null && queen.getRow() != null).collect(Collectors.groupingBy(Queen::getColumn, Collectors.groupingBy(Queen::getRow)));System.out.println("|     | " + columnList.stream().map(room -> String.format("%-3s", room.getIndex())).collect(Collectors.joining(" | ")) + " |");System.out.println("|" + "-----|".repeat(columnList.size() + 1));for (Column column : columnList) {List<List<Queen>> cellList = rowList.stream().map(row -> {Map<Row, List<Queen>> byRowMap = queenMap.get(column);if (byRowMap == null) {return Collections.<Queen>emptyList();}List<Queen> cellQueenList = byRowMap.get(row);if (cellQueenList == null) {return Collections.<Queen>emptyList();}return cellQueenList;}).collect(Collectors.toList());System.out.println("| " + String.format("%-3s", column.getIndex()) + " | "+ cellList.stream().map(cellQueenList -> String.format("%-3s",cellQueenList.stream().map(queen -> queen.getId().toString()).collect(Collectors.joining(", ")))).collect(Collectors.joining(" | "))+ " |");System.out.println("|" + "-----|".repeat(columnList.size() + 1));}List<Queen> unassignedQueens = queenList.stream().filter(Queen -> Queen.getColumn() == null || Queen.getRow() == null).collect(Collectors.toList());if (!unassignedQueens.isEmpty()) {System.out.println("");System.out.println("Unassigned Queens");for (Queen Queen : unassignedQueens) {System.out.println("  " + Queen.getColumn() + " - " + Queen.getRow());}}}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/36219.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/36219.shtml
英文地址,請注明出處:http://en.pswp.cn/news/36219.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

如何做好一名網絡工程師?具體實踐?

預防問題 – 資格與認證 在安裝線纜或升級網絡時測試線纜是預防問題的有效方式。對已安裝布線進行測試的方法有兩種。 資格測試確定布線是否有資格執行某些操作 — 換言之&#xff0c;支持特定網絡速度或應用。盡管“通過”認證測試也表明按標準支持某一網絡速度或應用的能力…

Redux - Redux在React函數式組件中的基本使用

文章目錄 一&#xff0c;簡介二&#xff0c;安裝三&#xff0c;三大核心概念Store、Action、Reducer3.1 Store3.2 Reducer3.3 Action 四&#xff0c;開始函數式組件中使用4.1&#xff0c;引入store4.1&#xff0c;store.getState()方法4.3&#xff0c;store.dispatch()方法4.4&…

cookie和session的區別及原理

Cookie概念 在瀏覽某些 網站 時,這些網站會把 一些數據存在 客戶端 , 用于使用網站 等跟蹤用戶,實現用戶自定義 功能. 是否設置過期時間: 如果不設置 過期時間,則表示這個 Cookie生命周期為 瀏覽器會話期間 , 只要關閉瀏覽器,cookie就消失了. 這個生命期為瀏覽會話期的cookie,就…

其他行業跳槽轉入計算機領域簡單看法

其他行業跳槽轉入計算機領域簡單看法 本人選擇從以下幾個方向談談自己的想法和觀點。 如何規劃才能實現轉碼 自我評估和目標設定&#xff1a;首先&#xff0c;你需要評估自己的技能和興趣&#xff0c;確定你希望在計算機領域從事的具體職位或領域。這有助于你更好地規劃學習路…

深入了解 Rancher Desktop 設置

Rancher Desktop 設置的全面概述 Rancher Desktop 擁有方便、強大的功能&#xff0c;是最佳的開發者工具之一&#xff0c;也是在本地構建和部署 Kubernetes 的最快捷方式。 本文將介紹 Rancher Desktop 的功能和特性&#xff0c;以及 Rancher Desktop 作為容器管理平臺和本地…

人工智能原理(2)

目錄 一、知識與知識表示 1、知識 2、知識表示 3、知識表示方法 二、謂詞邏輯表示法 1、命題邏輯 2、謂詞邏輯 三、產生式表達法 1、知識的表示方法 2、產生式系統組成 3、推理方式 4、產生式表示法特點 四、語義網絡 1、概念及結構 2、語義網絡的基本語義聯系 …

zookeeper案例

目錄 案例一&#xff1a;服務器動態上下線 服務端&#xff1a; &#xff08;1&#xff09;先獲取zookeeper連接 &#xff08;2&#xff09;注冊服務器到zookeeper集群&#xff1a; &#xff08;3&#xff09;業務邏輯&#xff08;睡眠&#xff09;&#xff1a; 服務端代碼…

Java+Excel+POI+testNG基于數據驅動做一個簡單的接口測試【杭州多測師_王sir】

一、創建一個apicases.xlsx放入到eclipse的resource里面&#xff0c;然后refresh刷新一下 二、在pom.xml文件中加入poi和testng的mvn repository、然后在eclipse的對應目錄下放入features和plugins&#xff0c;重啟eclipse就可以看到testNG了 <!--poi excel解析 --><d…

運維監控學習筆記3

DELL的IPMI頁面的登錄&#xff1a; 風扇的狀態&#xff1a; 電源溫度&#xff1a;超過70度就告警&#xff1a; 日志信息&#xff1a; 可以看到更換過磁盤。 iDRAC的設置 虛擬控制臺&#xff1a;啟動遠程控制臺&#xff1a; 可以進行遠程控制。 機房工程師幫我們接遠程控制&…

【云原生】kubernetes中容器的資源限制

目錄 1 metrics-server 2 指定內存請求和限制 3 指定 CPU 請求和限制 資源限制 在k8s中對于容器資源限制主要分為以下兩類: 內存資源限制: 內存請求&#xff08;request&#xff09;和內存限制&#xff08;limit&#xff09;分配給一個容器。 我們保障容器擁有它請求數量的…

【云原生】K8S集群

目錄 一、調度約束1.1 POT的創建過程1.1調度過程 二、指定節點調度2.1 通過標簽選擇節點 三、親和性3.1requiredDuringSchedulingIgnoredDuringExecution&#xff1a;硬策略3.1 preferredDuringSchedulingIgnoredDuringExecution&#xff1a;軟策略3.3Pod親和性與反親和性3.4使…

(2)原神角色數據分析-2

功能一&#xff1a; 得到某個屬性的全部角色&#xff0c;將其封裝在class中 """各元素角色信息&#xff1a;一對多""" from pandas import DataFrame, Series import pandas as pd import numpy as npclass FindType:# 自動執行&#xff0c;將…

山東布谷科技直播平臺搭建游戲開發技術分享:數據存儲的重要意義

在市場上的熱門的直播平臺中&#xff0c;有很多小程序為用戶提供各種各樣的功能&#xff0c;這其中就有很多游戲小程序&#xff0c;當今社會獨生子女眾多&#xff0c;很多作為獨生子女的用戶都會去選擇一個能夠社交互動的APP來填補內心的空虛&#xff0c;而直播平臺的實時互動的…

SAP 選擇屏幕組件名描述翻譯時字符長度不夠問題處理

問題&#xff1a;有時候我們在開發report程序的時候&#xff0c;要求程序顯示支持中英文&#xff0c;如果程序是在中文環境下開發的時候&#xff0c;需要進行翻譯處理&#xff0c;但是我們發現選擇屏幕上的組件的描述支持的默認長度是30位&#xff0c;如果超過該如何處理呢 解…

《路由與交換技術》讀書筆記

小小感悟 工作近3年&#xff0c;基本沒去看路由交換相關書籍&#xff0c;趁著搬家后&#xff0c;周末閑暇時間&#xff0c;快速看了一遍《路由與交換技術》&#xff0c;溫習了一遍&#xff0c;很有收獲&#xff0c;以后還是要多花時間看看其他類型的書。 讀書筆記 1.1 移動通…

構建一個LLM應用所需的所有信息

一、說明 您是否對大型語言模型&#xff08;LLM&#xff09;的潛力感興趣&#xff0c;并渴望創建您的第一個基于LLM的應用程序&#xff1f;或者&#xff0c;也許您是一位經驗豐富的開發人員&#xff0c;希望簡化工作流程&#xff1f;看看DemoGPT就是您的最佳選擇。該工具旨在簡…

【軟件測試】Linux環境下Docker搭建+Docker搭建MySQL服務(詳細)

目錄&#xff1a;導讀 前言 一、Python編程入門到精通二、接口自動化項目實戰三、Web自動化項目實戰四、App自動化項目實戰五、一線大廠簡歷六、測試開發DevOps體系七、常用自動化測試工具八、JMeter性能測試九、總結&#xff08;尾部小驚喜&#xff09; 前言 Linux之docker搭…

CDN(內容分發網絡)

CDN的全稱是 Content Delivery Network, 即內容分發網絡。CDN是構建在現有網絡基礎之上的智能虛擬網絡&#xff0c;依靠部署在各地的邊緣服務器&#xff0c;通過中心平臺的負載均衡、內容分發、調度等功能模塊&#xff0c;使用戶就近獲取所需內容&#xff0c;降低網絡擁塞&a…

詳談MongoDB的那些事

概念區分 什么是關系型數據庫 關系型數據庫&#xff08;Relational Database&#xff09;是一種基于關系模型的數據庫管理系統&#xff08;DBMS&#xff09;。在關系型數據庫中&#xff0c;數據以表格的形式存儲&#xff0c;表格由行和列組成&#xff0c;行表示數據記錄&…

神秘的ip地址8.8.8.8,到底是什么類型的DNS服務器?

下午好&#xff0c;我的網工朋友。 DNS&#xff0c;咱們網工配置網絡連接或者路由器時&#xff0c;高低得和這玩意兒打交道吧。 它是互聯網中用于將人類可讀的域名&#xff08;例如http://www.example.com&#xff09;轉換為計算機可理解的IP地址&#xff08;例如192.0.2.1&a…