-
Notifications
You must be signed in to change notification settings - Fork 0
/
N-Queens_Simulated_Annealing.java
125 lines (106 loc) · 2.7 KB
/
N-Queens_Simulated_Annealing.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package assignment_1;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static Scanner input = new Scanner(System.in);
public static int N;
public static void main(String[] args) {
double temp = 1000;
double decay = 0.98;
System.out.print("Please select the N value: ");
N = input.nextInt();
long startTime = System.nanoTime();
int[][] board = new int[N][N];
for(int i = 0; i<N; i++) {
Arrays.fill(board[i], 0);
int z = (int) (Math.random()*N);
board[i][z] = 1;
}
printBoard(board);
System.out.println("\n");
do {
int[][] newState = neighbour(board);
int cost = cost(board);
int newCost = cost(newState);
if(newCost < cost) {
board = newState;
temp = temp * decay;
}
else if(newCost >= cost) {
double prob = Math.exp((-1)*((newCost - cost)/temp));
if(Math.random() <= prob) {
board = newState;
}
temp = temp * decay;
}
//resets temp if plateaus or stalls
if(temp< 1.0E-300) temp = 1000;
}while(cost(board) != 0);
long endTime = System.nanoTime();
printBoard(board);
System.out.println("\n Runtime: "+(double)((double)(endTime - startTime)/1000000));
}
private static int conflictNum(int[][] board,int row, int col) {
int conflicts = 0;
//scans column
for(int x=0;x<N;x++) {
conflicts += board[x][col];
}
conflicts -= 1;
//scans diagonals
for(int i =0;i<N;i++) {
for(int j=0;j<N;j++) {
if(i!=row && board[i][j] == 1 && ((i-j == row-col)||(i+j == row+col))) {
conflicts += 1;
}
}
}
return conflicts;
}
private static int cost(int[][] board) {
int conflicts = 0;
for(int x =0;x<N;x++) {
for(int y=0;y<N;y++) {
if(board[x][y] == 1) {
conflicts += conflictNum(board,x,y);
}
}
}
return conflicts;
}
private static int[][] neighbour(int[][] board){
int[][] newBoard = new int[N][N];
//deep copy of board
for(int x=0;x<N;x++) {
for(int y=0;y<N;y++) {
newBoard[x][y] = board[x][y];
}
}
int row = (int)(Math.random()*N);
int currentPos = getCol(board,row);
newBoard[row][currentPos] = 0;
int pos = (int)Math.random()*N;
while(pos == currentPos) {
pos=(int)(Math.random()*N);
}
newBoard[row][pos] = 1;
return newBoard;
}
private static int getCol(int[][] board, int row) {
int col = 0;
for(int i = 0;i<N;i++) {
if(board[row][i] == 1) {
col = i;
}
}
return col;
}
private static void printBoard(int[][] board) {
for(int i=0;i<N;i++) {
for(int j=0;j<N;j++) {
System.out.print(board[i][j] + " ");
}
System.out.println("");
}
}
}