自己写的模拟退火方法求解八皇后问题, 大家帮看看, 下周交作业
import java.util.Random;
import java.util.Date;
public class NQueenSimulatedAnnealing{
private int[] board;
private int[] test;
private int dim;
private Random ran;
private double currentTemperature;
private double coolingCoefficient;
private int internalIter; //number of swaps accepted.
private int initialConflicts, currentConflicts, conflictsDifference;
private int conflictPosition; //a cursor to circulate the whole array, to record a conflict position
public static void main(String[] args){
// int inDimension;
// double inInitialTemperature, inInitialCoolingCoefficient;
// if (args.length == 0){
// System.out.println("At least the dimension of the board is necessary!");
// return;
// }
// inDimension = Integer.parseInt(args[0]);
// if (args.length > 1){
// inInitialTemperature = Double.parseDouble(args[1]);
// if (args.length > 2){
// inInitialCoolingCoefficient = Double.parseDouble(args[2]);
// }else{
// inInitialCoolingCoefficient = 0.995;
// }
// }else{
// inInitialTemperature = inDimension;
// inInitialCoolingCoefficient = 0.995;
// }
// NQueenSimulatedAnnealing nqsa = new NQueenSimulatedAnnealing(inDimension);
// System.out.println("Board dimension: " + nqsa.dim);
// System.out.println("Initial Conflicts: " + nqsa.getConflicts());
// nqsa.solve(inInitialTemperature, inInitialCoolingCoefficient);
NQueenSimulatedAnnealing nqsa = new NQueenSimulatedAnnealing(10000);
System.out.println("Board dimension: " + nqsa.dim);
System.out.println("Initial Conflicts: " + nqsa.getConflicts());
nqsa.solve(1000, 0.99);
}
public NQueenSimulatedAnnealing(){
this(100);
}
public NQueenSimulatedAnnealing(int dimension){
dim = dimension;
internalIter = 0;
conflictPosition = 0;
ran = new Random(new Date().getTime()); //new random sead
board = new int[dim];
for (int i = 0; i < dim; i++){ //set all Queens at the diagonal
board[i] = i;
}
test = board.clone(); //copy one copy of board to test.
initialConflicts = currentConflicts = this.getConflicts();
}
public void solve(double inInitialTemperature, double inCoolingCoefficient){
currentTemperature = inInitialTemperature;
coolingCoefficient = inCoolingCoefficient;
testQueen();
if (dim <= 50){
display();
}else{
System.out.println("\nSolution found! Too large to print!");
}
}
private void testQueen(){
int swap1, swap2;
while(true){ //control temperature
while(true){ //find an acceptable solution
swap1 = findConflictPosition(); //first swap position: a conflict position
swap2 = ran.nextInt(dim); //second swap position: a random position
swap(swap1, swap2); //swap, in array test[]
conflictsDifference = getConflictsDifference(swap1, swap2); //the differece after and before swap, by comparing board[] and test[]
if (conflictsDifference < 0){ //a better solution
swapAccepted(); //accept
break;
}else{ //a worse solution
if(Math.exp(-conflictsDifference/currentTemperature) > ran.nextDouble()){ //still accepted by a certain probability
swapAccepted();
break;
}else{
test = board.clone(); //cancel the swap, by copy back from board[]
}
}
}
printSwapSummary(); //after a new solution is accepted, print the summary
if (currentConflicts == 0 ){ //solved!
break;
}else{
currentTemperature *= coolingCoefficient; //decrease temperature
}
}
}
private int findConflictPosition(){
int i;
while (true){
for (i = 0; i < dim; i++){
if(Math.abs(conflictPosition - i) == Math.abs(board[conflictPosition] - board[i])){ //conflict!
if (conflictPosition != i){
return conflictPosition;
}
}
}
conflictPosition++;
if (conflictPosition == dim) conflictPosition = 0; //start from the beginning is it reaches the end
}
}
private int getConflictsDifference(int swap1, int swap2){ //only check the two Queens swapped, return the difference.
int oldNumber = 0;
int newNumber = 0;
int i = 0;
for (i = 0; i < dim; i++){
if(Math.abs(swap1 - i) == Math.abs(board[swap1] - board[i])){
oldNumber++;
}
if(Math.abs(swap2 - i) == Math.abs(board[swap2] - board[i])){
oldNumber++;
}
if(Math.abs(swap1 - i) == Math.abs(test[swap1] - test[i])){
newNumber++;
}
if(Math.abs(swap2 - i) == Math.abs(test[swap2] - test[i])){
newNumber++;
}
}
return newNumber - oldNumber;
}
private int getConflicts(){ //iteration to get the total conflicts
int i, j;
int counts = 0;
for (i = 0; i < dim; i++){
for (j = i + 1; j < dim; j++){
int temp = test[i] - test[j];
if (temp == i - j){
counts++;
}else if(temp == j - i){
counts++;
}
}
}
return counts;
}
private void swap(int i, int j){ //swap two columns, since only one queen per row and column
int temp = test[i];
test[i] = test[j];
test[j] = temp;
}
private void display(){
int cursor = 0;
System.out.printf("\n*** One Solution ***\n");
while(cursor < dim){
for (int i = 0; i < test[cursor]; i++){
System.out.print("- ");
}
System.out.print("Q ");
for (int i = test[cursor] + 1; i < dim; i++){
System.out.print("- ");
}
System.out.println();
cursor++;
}
System.out.println("*** Solutions end ***\n");
}
private void swapAccepted(){
board = test.clone();
currentConflicts += conflictsDifference;
}
private void printSwapSummary(){
double tempDraw;
System.out.printf("%6d:%8d:%10.2f \t|", ++internalIter, currentConflicts, currentTemperature);
tempDraw = 50. / initialConflicts * currentConflicts;
for (int i = 1; i< tempDraw; i++){
System.out.print("#");
}
System.out.print("\n");
}
}
import java.util.Date;
public class NQueenSimulatedAnnealing{
private int[] board;
private int[] test;
private int dim;
private Random ran;
private double currentTemperature;
private double coolingCoefficient;
private int internalIter; //number of swaps accepted.
private int initialConflicts, currentConflicts, conflictsDifference;
private int conflictPosition; //a cursor to circulate the whole array, to record a conflict position
public static void main(String[] args){
// int inDimension;
// double inInitialTemperature, inInitialCoolingCoefficient;
// if (args.length == 0){
// System.out.println("At least the dimension of the board is necessary!");
// return;
// }
// inDimension = Integer.parseInt(args[0]);
// if (args.length > 1){
// inInitialTemperature = Double.parseDouble(args[1]);
// if (args.length > 2){
// inInitialCoolingCoefficient = Double.parseDouble(args[2]);
// }else{
// inInitialCoolingCoefficient = 0.995;
// }
// }else{
// inInitialTemperature = inDimension;
// inInitialCoolingCoefficient = 0.995;
// }
// NQueenSimulatedAnnealing nqsa = new NQueenSimulatedAnnealing(inDimension);
// System.out.println("Board dimension: " + nqsa.dim);
// System.out.println("Initial Conflicts: " + nqsa.getConflicts());
// nqsa.solve(inInitialTemperature, inInitialCoolingCoefficient);
NQueenSimulatedAnnealing nqsa = new NQueenSimulatedAnnealing(10000);
System.out.println("Board dimension: " + nqsa.dim);
System.out.println("Initial Conflicts: " + nqsa.getConflicts());
nqsa.solve(1000, 0.99);
}
public NQueenSimulatedAnnealing(){
this(100);
}
public NQueenSimulatedAnnealing(int dimension){
dim = dimension;
internalIter = 0;
conflictPosition = 0;
ran = new Random(new Date().getTime()); //new random sead
board = new int[dim];
for (int i = 0; i < dim; i++){ //set all Queens at the diagonal
board[i] = i;
}
test = board.clone(); //copy one copy of board to test.
initialConflicts = currentConflicts = this.getConflicts();
}
public void solve(double inInitialTemperature, double inCoolingCoefficient){
currentTemperature = inInitialTemperature;
coolingCoefficient = inCoolingCoefficient;
testQueen();
if (dim <= 50){
display();
}else{
System.out.println("\nSolution found! Too large to print!");
}
}
private void testQueen(){
int swap1, swap2;
while(true){ //control temperature
while(true){ //find an acceptable solution
swap1 = findConflictPosition(); //first swap position: a conflict position
swap2 = ran.nextInt(dim); //second swap position: a random position
swap(swap1, swap2); //swap, in array test[]
conflictsDifference = getConflictsDifference(swap1, swap2); //the differece after and before swap, by comparing board[] and test[]
if (conflictsDifference < 0){ //a better solution
swapAccepted(); //accept
break;
}else{ //a worse solution
if(Math.exp(-conflictsDifference/currentTemperature) > ran.nextDouble()){ //still accepted by a certain probability
swapAccepted();
break;
}else{
test = board.clone(); //cancel the swap, by copy back from board[]
}
}
}
printSwapSummary(); //after a new solution is accepted, print the summary
if (currentConflicts == 0 ){ //solved!
break;
}else{
currentTemperature *= coolingCoefficient; //decrease temperature
}
}
}
private int findConflictPosition(){
int i;
while (true){
for (i = 0; i < dim; i++){
if(Math.abs(conflictPosition - i) == Math.abs(board[conflictPosition] - board[i])){ //conflict!
if (conflictPosition != i){
return conflictPosition;
}
}
}
conflictPosition++;
if (conflictPosition == dim) conflictPosition = 0; //start from the beginning is it reaches the end
}
}
private int getConflictsDifference(int swap1, int swap2){ //only check the two Queens swapped, return the difference.
int oldNumber = 0;
int newNumber = 0;
int i = 0;
for (i = 0; i < dim; i++){
if(Math.abs(swap1 - i) == Math.abs(board[swap1] - board[i])){
oldNumber++;
}
if(Math.abs(swap2 - i) == Math.abs(board[swap2] - board[i])){
oldNumber++;
}
if(Math.abs(swap1 - i) == Math.abs(test[swap1] - test[i])){
newNumber++;
}
if(Math.abs(swap2 - i) == Math.abs(test[swap2] - test[i])){
newNumber++;
}
}
return newNumber - oldNumber;
}
private int getConflicts(){ //iteration to get the total conflicts
int i, j;
int counts = 0;
for (i = 0; i < dim; i++){
for (j = i + 1; j < dim; j++){
int temp = test[i] - test[j];
if (temp == i - j){
counts++;
}else if(temp == j - i){
counts++;
}
}
}
return counts;
}
private void swap(int i, int j){ //swap two columns, since only one queen per row and column
int temp = test[i];
test[i] = test[j];
test[j] = temp;
}
private void display(){
int cursor = 0;
System.out.printf("\n*** One Solution ***\n");
while(cursor < dim){
for (int i = 0; i < test[cursor]; i++){
System.out.print("- ");
}
System.out.print("Q ");
for (int i = test[cursor] + 1; i < dim; i++){
System.out.print("- ");
}
System.out.println();
cursor++;
}
System.out.println("*** Solutions end ***\n");
}
private void swapAccepted(){
board = test.clone();
currentConflicts += conflictsDifference;
}
private void printSwapSummary(){
double tempDraw;
System.out.printf("%6d:%8d:%10.2f \t|", ++internalIter, currentConflicts, currentTemperature);
tempDraw = 50. / initialConflicts * currentConflicts;
for (int i = 1; i< tempDraw; i++){
System.out.print("#");
}
System.out.print("\n");
}
}
...全文
相关推荐
爬山法、模拟退火法、遗传算法实现八皇后问题
在计算机科学领域,优化问题的求解方法多样,其中,爬山法、模拟退火法和遗传算法是三种常见的全局优化技术。它们被应用于解决各种复杂问题,包括经典的八皇后问题。
人工智能:用爬山法、模拟退火算法实现八皇后和八数码问题
这里简单介绍下局部搜索算法。局部搜索算法是对一个或多个状态进行评价和修改,而不是系统地从初始状态开始的路径。这些算法适用于关注那些关注解状态而不是路径代价的问题。局部搜索算法从单个当前节点出发,通常只移动到它的临近状态,一般保存搜索路径。局部搜素不是系统化的,但有两个关键的优点。 1. 只用很少的内存——通常是常熟 2. 经常能在系统化算法不适用的很大或无限的状态空间中找到合理的解。爬山法(最陡
基于遗传算法的八皇后问题
遗传算法 遗传算法是随机束搜索的一个变型,它通过把两个父状态结合来生成后继,而不是通过修改单一状态进行。 设计思路 运行结构 总结
202102模拟退火算法求解流水车间调度问题及Matlab编程实现.pdf
在流水车间调度问题的求解中,模拟退火算法可以用来寻找接近最优的作业加工顺序。当需要处理的作业和设备数量增多时,全排列求解的时间复杂度会急剧增加,此时采用模拟退火算法可以有效降低求解时间。
遗传模拟退火算法求解TSP问题matlab代码,模拟退火算法解决tsp问题,matlab
文件名“遗传模拟退火算法求解TSP问题matlab代码”可能包含以下内容:1. tsp问题的数据结构,如城市坐标。2. 初始化解的方法,如随机生成路径。3. 计算路径长度的函数。4.


Java SE
