Hi,
I'm novoice to java. I'm trying a program for place 8 X’s on the board with 64 boxes(8*8 matrix) in such a way that:
1. there is at the most one X in any box
2. no two X’s are on the same row
3. no two X’s are on the same column
4. no two X’s are on the same diagonal
Write a Java application program that takes a brute-force approach using random
number generation to find one such placement and display it on the screen.
Basically, the program will do the following until it finds a solution:
1. set n = 1
2. For n =1 to 8
a. check if there are any other boxes where an X can be placed without violating any
of the constraints that we have specified above. if no, go to step 1
b. choose a random box to place the nth X
c. find out if placing an X in that box violates any of the constraints that we have
specified above.
If no, place the nth X in that box, increment n by 1.
Below is the code, that i have tried so far...Please help me to finish this program as soon as possible...Please Help me...It's very urgent
import java.util.Random; public class Assignment1_HondalCarlos { static int res; public static void main(String[] args) { char[][] board = new char[8][8]; Random randomGenerator = new Random(); int randomRow =0; int randomColumn=0; for(int a=0;a<8;a++) { for(int b=0;b<8;b++) { board[a][b]='-'; } } for(int a=0;a<8;a++) { for(int b=0;b<8;b++) { System.out.print(board[a][b] +" "); } System.out.println(" "); } for(int n = 0; n < 8; n++) { randomRow = randomGenerator.nextInt(8); randomColumn = randomGenerator.nextInt(8); boolean test = false; testconstraints(board, randomRow, randomColumn); if(res==0) { board[randomRow][randomColumn] = 'X'; } } for(int j=0;j<8;j++) { for(int k=0;k<8;k++) { System.out.print(board[j][k] +" "); } System.out.println(" "); } } public static int testconstraints(char[][] board,int rowCheck, int colCheck) { System.out.println("Row :" + rowCheck + " Column : " + colCheck); if(board[rowCheck][0]=='X' || board[rowCheck][1]=='X' ||board[rowCheck][2]=='X' ||board[rowCheck][3]=='X' ||board[rowCheck][4]=='X' ||board[rowCheck][5]=='X' ||board[rowCheck][6]=='X' ||board[rowCheck][7]=='X' ) { if(board[0][colCheck]=='X' || board[1][colCheck]=='X' || board[2][colCheck]=='X' || board[3][colCheck]=='X' || board[4][colCheck]=='X' || board[5][colCheck]=='X' || board[6][colCheck]=='X' || board[7][colCheck]=='X' ) { res= 1; } } else { res = 0; } return 0; } }