SlideShare a Scribd company logo
1 of 12
Download to read offline
need help with this java lab: please read below and follow the steps! Copy and paste the code at
the bottom into your ide and go from there, please do not write a whole new program!
The purpose of this lab is to give you an opportunity to make use of a stack in the
implementation of a backtracking algorithm.
This problem is generally referred to as the N Queens problem. The gist of the problem is to
create an algorithm which can position N queens on a chess board so none of the queens can
attack any other queen. For those of you who may not be familiar with chess, the queen can
move horizontally, vertically, and diagonally. In the generalized N Queens problem, N represents
the number of rows and columns of the game board and the number of queens that must be
placed on the board in safe positions.
we will NOT be using recursion in any way to solve this problem.
The basic strategy that we will employ to solve this problem is to use backtracking. In this
particular case, what backtracking means is that we will make a move that is safe for a queen at
the time we make the move, but later on, we may discover that we are stuck and there is no safe
move available for the next queen we are trying to place on the board, so we must backtrack.
That means we will go back to the previous queen’s move, undo that move, and continue
searching for another safe place to put that queen. We will use the stack to remember where we
have placed queens on the board and when we need to back up, the queen at the top of the stack
will be popped and we will use that queen’s position to resume the search for the next safe
location.Stradegy below:
There are N rows. When a queen is placed into a row, that row cannot be used by other queens.
There are N columns. When a queen is placed into a column, that column cannot be used by
other queens.
There are 2 sets of diagonals to be concerned with, diagonals running upper left to lower right
and diagonals running upper right to lower left. There is a simple mathematical relationship
between N and the number of diagonals in each direction. When a queen is placed onto the
board, one left to right diagonal is no longer safe for other queens, and one right to left diagonal
is no longer safe for other queens.
Our approach to placing the queens on the board will be to use nested loops. As an example the
outer loop will be in control of which column we are currently searching for a spot to place a
queen. So, the first queen we place will be in column 0, and when the outer loop has completed
we will have placed N queens on the board, one in each column.
The inner loop will iterate through the rows, from 0 to N-1 until it finds a row R such that row R
is not taken by another queen, AND the 2 diagonals which intersect row R and the current
column are not taken by another queen. IF we find such a safe location, we push the current row,
column value onto a stack. Note: we can use the Java Point class to store the row and column
numbers in the x, y values of a Point object. By placing a queen’s location information into the
stack, we have affected the state of the board. We must update the state information to reflect
that a row is no longer safe for other queens. We also must update the state of the two diagonals
which intersect with the queen’s row, column position to indicate that those diagonals are no
longer available to other queens to be placed later. After updating the state information, we can
break out of the inner loop and continue on to the next column in the outer loop.
The backtracking aspect of this exercise occurs when the inner loop fails to find a spot to place a
queen in the current column. Inside the inner loop, we need to recognize that we have checked
position (row N-1, current column) and found that it is not safe. Therefore there is no safe place
for a queen in this column. Since we are stuck, we need to back up and try a different placement
for the previously placed queen. To backtrack, we need to undo the actions taken when we
placed the last queen onto the stack. That means pop the last queen off the stack, mark the row
and diagonals associated with that queen’s position as available again, and reset the row and
column loop control variables back to the point where they were when this queen was pushed
onto the stack (ie row = poppedPoint.x, column = poppedPoint.y). After backtracking the row
loop will continue to the next row to check if that row, column position is safe.
I am providing you with a partially completed Java FX project for this project. The project I am
giving you contains 2 classes. The GameBoard class provides methods for creation of the game
board based on the size given to its constructor. It also provides methods for placing and
removing a queen from a specific row, column position on the game board.
The JavaFxQueens class is the main application class. It determines what size the game board is
to be, creates an GameBoard object, and places the game board into a scene on the stage. It also
starts up a thread which will find safe places on the board for all the queens.
The placeQueens method in the JavaFxQueens class has not been completed. You must write the
code needed to find safe locations for all the queens. Whenever you find a safe place and push a
row, col position onto the stack, you must also call the placeQueen method on the GameBoard
object to draw that queen on the board. Whenever you backtrack and pop a row, col position off
the stack, you must also call the removeQueen method on the GameBoard object to remove that
queen from the game board display. Note, that after calling either one of these 2 methods, you
must call the delay method (which is provided) to slow down the rate at which moves are drawn
on the board so that every queen placed or removed is visible on the display for a reasonable
amount of time.
Think very carefully about how you want to organize the data which captures the state of the
game board (rows, diagonals). You do not need an actual representation of the game board (ie.
no 2 dimensional array). Also think carefully about how to mathematically capture the
relationship between a row, column position and which diagonals intersect that position. Part of
creating efficient programs is designing clever data representations which can be accessed in
very efficient ways from known information.
here is the code: please copy the java queens class and the gameboard class into your ide and
read the above to solve.
****javaQueens****
package javafxqueens;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javax.swing.JOptionPane;
/**
*
* @author RVolkers
*/
public class JavaFxQueens extends Application implements Runnable {
private GameBoard board;
private int boardSize = 0;
@Override
public void start(Stage primaryStage) {
// Get the size of the game board from the user. Must be at least 5.
while(boardSize < 5)
{
boardSize = Integer.parseInt(JOptionPane.showInputDialog("Enter size of chess board."));
}
board = new GameBoard(boardSize);
// The game board calculates how much display area it will need to display properly
Scene scene = new Scene(board, board.getDisplaySize(), board.getDisplaySize());
primaryStage.setTitle("N Queens");
primaryStage.setScene(scene);
primaryStage.show();
// Since the main thread is responsible for doing all the GUI updating,
// we need a separate thread to process the placement of queens. That thread
// will call methods on the GameBoard to tell the main thread where to place
// or remove queens on the board.
Thread thread = new Thread(this);
thread.start();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
// Must do the main processing in a separate thread, so this class
// implements the Runnable interface.
@Override
public void run() {
// This thread calls a private method to figure out where the queens go
placeQueens();
}
// Used to slow down moves to enable seeing the board placement change
// as each queen is placed or removed from the board
private void delay()
{
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
}
}
// Figure out where to place the queens here....
// Call placeQueen and removeQueen methods on the gameBoard object when needed
private void placeQueens()
{
//insert new code here!
}
}
******gameboard******
package javafxqueens;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
/**
*
* @author RVolkers
*/
public class GameBoard extends GridPane {
private final int ButtonSize = 110;
private final int GapSize = 5;
private int size;
private Button[][] board;
public GameBoard() {
super();
setHgap(GapSize);
setVgap(GapSize);
setAlignment(Pos.CENTER);
setPadding(new Insets(GapSize, GapSize, GapSize, GapSize));
size = 8;
createBoard();
}
public GameBoard(int n) {
super();
setHgap(GapSize);
setVgap(GapSize);
setAlignment(Pos.CENTER);
setPadding(new Insets(GapSize, GapSize, GapSize, GapSize));
size = n;
createBoard();
}
private void createBoard() {
// Create an array to hold references to all the buttons on the board.
board = new Button[size][size];
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
// Create each button with alternating colors
Button b = new Button();
b.setPrefSize(ButtonSize, ButtonSize);
if ((row + col) % 2 == 0) {
b.setStyle("-fx-background-color: red");
} else {
b.setStyle("-fx-background-color: black");
}
// Add the button to the board and to the GridPane
board[row][col] = b;
add(b, col, row);
}
}
}
// Calculate the size of the display based on the size
// of the buttons and the size of the gaps between buttons.
public double getDisplaySize() {
return size * ButtonSize + (size + 1) * GapSize;
}
// Verify that the row and col parameters are valid.
// Pass a runnable object to the main thread to update the GUI
// by adding the queen graphic to the appropriate button on the board
public void placeQueen(int row, int col) throws IllegalArgumentException {
if (row < 0 || row >= size || col < 0 || col >= size) {
throw new IllegalArgumentException("Row or column out of bounds");
}
Platform.runLater(() -> {
board[row][col].setGraphic(new ImageView("queen.gif"));
});
}
// Verify that the row and col parameters are valid.
// Pass a runnable object to the main thread to update the GUI
// by removing the queen graphic from the appropriate button on the board
public void removeQueen(int row, int col) throws IllegalArgumentException {
if (row < 0 || row >= size || col < 0 || col >= size) {
throw new IllegalArgumentException("Row or column out of bounds");
}
Platform.runLater(() -> {
board[row][col].setGraphic(null);
});
}
}
Solution
i add some methods for display the queens as Q and move the queens
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javax.swing.JOptionPane;
public class JavaFxQueens extends Application implements Runnable {
private GameBoard board;
private int boardSize = 0;
@Override
public void start(Stage primaryStage) {
// Get the size of the game board from the user. Must be at least 5.
while(boardSize < 5)
{
boardSize = Integer.parseInt(JOptionPane.showInputDialog("Enter size of chess board."));
}
board = new GameBoard(boardSize);
// The game board calculates how much display area it will need to display properly
Scene scene = new Scene(board, board.getDisplaySize(), board.getDisplaySize());
primaryStage.setTitle("N Queens");
primaryStage.setScene(scene);
primaryStage.show();
// Since the main thread is responsible for doing all the GUI updating,
// we need a separate thread to process the placement of queens. That thread
// will call methods on the GameBoard to tell the main thread where to place
// or remove queens on the board.
Thread thread = new Thread(this);
thread.start();
}
public static void main(String[] args) {
launch(args);
}
// Must do the main processing in a separate thread, so this class
// implements the Runnable interface.
@Override
public void run() {
// This thread calls a private method to figure out where the queens go
placeQueens();
}
// Used to slow down moves to enable seeing the board placement change
// as each queen is placed or removed from the board
private void delay()
{
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
}
}
// Figure out where to place the queens here....
// Call placeQueen and removeQueen methods on the gameBoard object when needed
//here we need on method for display the queens
public void showQueens(int[] s) {
int n = s.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (s[i] == j) {
System.out.print("Q");
} else {
System.out.print("");
}
}
System.out.println();
}
System.out.println();
}
public void placeQueens(int p, int n) {
for (int c = 0; c < n; c++) {
if (placeQueens(p, c)) {
s[r] = c;
if (r == n - 1) {
printQueens(s);
} else {
placeQueens(p + 1, n);
}
}
}
}
public void callplaceNqueens() {
placeQueens(0, s.length);
}
}
******gameboard******
package javafxqueens;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
/**
*
* @author RVolkers
*/
public class GameBoard extends GridPane {
private final int ButtonSize = 110;
private final int GapSize = 5;
private int size;
private Button[][] board;
public GameBoard() {
super();
setHgap(GapSize);
setVgap(GapSize);
setAlignment(Pos.CENTER);
setPadding(new Insets(GapSize, GapSize, GapSize, GapSize));
size = 8;
createBoard();
}
public GameBoard(int n) {
super();
setHgap(GapSize);
setVgap(GapSize);
setAlignment(Pos.CENTER);
setPadding(new Insets(GapSize, GapSize, GapSize, GapSize));
size = n;
createBoard();
}
private void createBoard() {
// Create an array to hold references to all the buttons on the board.
board = new Button[size][size];
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
// Create each button with alternating colors
Button b = new Button();
b.setPrefSize(ButtonSize, ButtonSize);
if ((row + col) % 2 == 0) {
b.setStyle("-fx-background-color: red");
} else {
b.setStyle("-fx-background-color: black");
}
// Add the button to the board and to the GridPane
board[row][col] = b;
add(b, col, row);
}
}
}
// Calculate the size of the display based on the size
// of the buttons and the size of the gaps between buttons.
public double getDisplaySize() {
return size * ButtonSize + (size + 1) * GapSize;
}
// Verify that the row and col parameters are valid.
// Pass a runnable object to the main thread to update the GUI
// by adding the queen graphic to the appropriate button on the board
public void placeQueen(int row, int col) throws IllegalArgumentException {
if (row < 0 || row >= size || col < 0 || col >= size) {
throw new IllegalArgumentException("Row or column out of bounds");
}
Platform.runLater(() -> {
board[row][col].setGraphic(new ImageView("queen.gif"));
});
}
// Verify that the row and col parameters are valid.
// Pass a runnable object to the main thread to update the GUI
// by removing the queen graphic from the appropriate button on the board
public void removeQueen(int row, int col) throws IllegalArgumentException {
if (row < 0 || row >= size || col < 0 || col >= size) {
throw new IllegalArgumentException("Row or column out of bounds");
}
Platform.runLater(() -> {
board[row][col].setGraphic(null);
});
}
}

More Related Content

Similar to need help with this java lab please read below and follow the steps.pdf

Read carefully and follow exactly Java You are to write a Breakou.pdf
Read carefully and follow exactly Java You are to write a Breakou.pdfRead carefully and follow exactly Java You are to write a Breakou.pdf
Read carefully and follow exactly Java You are to write a Breakou.pdf
rupeshmehta151
 
I need help with this assignment Ive gotten abit stuck with the cod.pdf
I need help with this assignment Ive gotten abit stuck with the cod.pdfI need help with this assignment Ive gotten abit stuck with the cod.pdf
I need help with this assignment Ive gotten abit stuck with the cod.pdf
Conint29
 
Im looking for coding help I dont really need this to be explained.pdf
Im looking for coding help I dont really need this to be explained.pdfIm looking for coding help I dont really need this to be explained.pdf
Im looking for coding help I dont really need this to be explained.pdf
contact41
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
Luis Goldster
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
Tony Nguyen
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
Fraboni Ec
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
James Wong
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
Young Alista
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
Harry Potter
 

Similar to need help with this java lab please read below and follow the steps.pdf (20)

N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
 
Copy of repast javagettingstarted
Copy of repast javagettingstartedCopy of repast javagettingstarted
Copy of repast javagettingstarted
 
Proyecto grupal algebra parcial ii
Proyecto grupal algebra parcial iiProyecto grupal algebra parcial ii
Proyecto grupal algebra parcial ii
 
ngAnimate crash course
ngAnimate crash coursengAnimate crash course
ngAnimate crash course
 
Support vector machines (svm)
Support vector machines (svm)Support vector machines (svm)
Support vector machines (svm)
 
Read carefully and follow exactly Java You are to write a Breakou.pdf
Read carefully and follow exactly Java You are to write a Breakou.pdfRead carefully and follow exactly Java You are to write a Breakou.pdf
Read carefully and follow exactly Java You are to write a Breakou.pdf
 
Codeware
CodewareCodeware
Codeware
 
I need help with this assignment Ive gotten abit stuck with the cod.pdf
I need help with this assignment Ive gotten abit stuck with the cod.pdfI need help with this assignment Ive gotten abit stuck with the cod.pdf
I need help with this assignment Ive gotten abit stuck with the cod.pdf
 
Im looking for coding help I dont really need this to be explained.pdf
Im looking for coding help I dont really need this to be explained.pdfIm looking for coding help I dont really need this to be explained.pdf
Im looking for coding help I dont really need this to be explained.pdf
 
Shoot-for-A-Star
Shoot-for-A-StarShoot-for-A-Star
Shoot-for-A-Star
 
Data Structure Lecture 4
Data Structure Lecture 4Data Structure Lecture 4
Data Structure Lecture 4
 
Read carefully. Im not sure if the point class is correct but postin.pdf
Read carefully. Im not sure if the point class is correct but postin.pdfRead carefully. Im not sure if the point class is correct but postin.pdf
Read carefully. Im not sure if the point class is correct but postin.pdf
 
PRML Chapter 6
PRML Chapter 6PRML Chapter 6
PRML Chapter 6
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 

More from arjuntiwari586

Which of the following is a trace element, required only in small amo.pdf
Which of the following is a trace element, required only in small amo.pdfWhich of the following is a trace element, required only in small amo.pdf
Which of the following is a trace element, required only in small amo.pdf
arjuntiwari586
 
Use the Java Thread class to demonstrate the following functionaliti.pdf
Use the Java Thread class to demonstrate the following functionaliti.pdfUse the Java Thread class to demonstrate the following functionaliti.pdf
Use the Java Thread class to demonstrate the following functionaliti.pdf
arjuntiwari586
 
The lineage that produced chimpanzees and humans split from other pri.pdf
The lineage that produced chimpanzees and humans split from other pri.pdfThe lineage that produced chimpanzees and humans split from other pri.pdf
The lineage that produced chimpanzees and humans split from other pri.pdf
arjuntiwari586
 
Prepare a 3-4 page, double-spaced paper (cite 3-4 reliable sources) .pdf
Prepare a 3-4 page, double-spaced paper (cite 3-4 reliable sources) .pdfPrepare a 3-4 page, double-spaced paper (cite 3-4 reliable sources) .pdf
Prepare a 3-4 page, double-spaced paper (cite 3-4 reliable sources) .pdf
arjuntiwari586
 

More from arjuntiwari586 (20)

Would you recomend that Miss E begin to take a vitamin or mineral su.pdf
Would you recomend that Miss E begin to take a vitamin or mineral su.pdfWould you recomend that Miss E begin to take a vitamin or mineral su.pdf
Would you recomend that Miss E begin to take a vitamin or mineral su.pdf
 
Which perspective best describes adolescenceWhen does adolescence.pdf
Which perspective best describes adolescenceWhen does adolescence.pdfWhich perspective best describes adolescenceWhen does adolescence.pdf
Which perspective best describes adolescenceWhen does adolescence.pdf
 
Which of the following is a trace element, required only in small amo.pdf
Which of the following is a trace element, required only in small amo.pdfWhich of the following is a trace element, required only in small amo.pdf
Which of the following is a trace element, required only in small amo.pdf
 
Which of the following enzymes has the ability to accomplish all thr.pdf
Which of the following enzymes has the ability to accomplish all thr.pdfWhich of the following enzymes has the ability to accomplish all thr.pdf
Which of the following enzymes has the ability to accomplish all thr.pdf
 
What risk are associated with pregnancySolutionThere are vari.pdf
What risk are associated with pregnancySolutionThere are vari.pdfWhat risk are associated with pregnancySolutionThere are vari.pdf
What risk are associated with pregnancySolutionThere are vari.pdf
 
What are the relative signal intensities for Grey and White matter u.pdf
What are the relative signal intensities for Grey and White matter u.pdfWhat are the relative signal intensities for Grey and White matter u.pdf
What are the relative signal intensities for Grey and White matter u.pdf
 
What is the ovum doing during the primary oocyte stageSolution.pdf
What is the ovum doing during the primary oocyte stageSolution.pdfWhat is the ovum doing during the primary oocyte stageSolution.pdf
What is the ovum doing during the primary oocyte stageSolution.pdf
 
What is the structural difference between the sugar found in RNA and.pdf
What is the structural difference between the sugar found in RNA and.pdfWhat is the structural difference between the sugar found in RNA and.pdf
What is the structural difference between the sugar found in RNA and.pdf
 
uìdyov fotect peaga e (or ways co profecé se p protect e . Haa .pdf
uìdyov fotect peaga e (or ways co profecé se p protect e . Haa .pdfuìdyov fotect peaga e (or ways co profecé se p protect e . Haa .pdf
uìdyov fotect peaga e (or ways co profecé se p protect e . Haa .pdf
 
Use the Java Thread class to demonstrate the following functionaliti.pdf
Use the Java Thread class to demonstrate the following functionaliti.pdfUse the Java Thread class to demonstrate the following functionaliti.pdf
Use the Java Thread class to demonstrate the following functionaliti.pdf
 
Turner suppressor genes.... prevent gene expression of oncogenes. pre.pdf
Turner suppressor genes.... prevent gene expression of oncogenes. pre.pdfTurner suppressor genes.... prevent gene expression of oncogenes. pre.pdf
Turner suppressor genes.... prevent gene expression of oncogenes. pre.pdf
 
This image is a reminder that statistical significant is often set at.pdf
This image is a reminder that statistical significant is often set at.pdfThis image is a reminder that statistical significant is often set at.pdf
This image is a reminder that statistical significant is often set at.pdf
 
The state diagram shown up corresponds to a circuit implementation th.pdf
The state diagram shown up corresponds to a circuit implementation th.pdfThe state diagram shown up corresponds to a circuit implementation th.pdf
The state diagram shown up corresponds to a circuit implementation th.pdf
 
The lineage that produced chimpanzees and humans split from other pri.pdf
The lineage that produced chimpanzees and humans split from other pri.pdfThe lineage that produced chimpanzees and humans split from other pri.pdf
The lineage that produced chimpanzees and humans split from other pri.pdf
 
production deviance postconventional level primary stakeholders perso.pdf
production deviance postconventional level primary stakeholders perso.pdfproduction deviance postconventional level primary stakeholders perso.pdf
production deviance postconventional level primary stakeholders perso.pdf
 
Question 19 (1 point) The DuPont identity breaks down return on equit.pdf
Question 19 (1 point) The DuPont identity breaks down return on equit.pdfQuestion 19 (1 point) The DuPont identity breaks down return on equit.pdf
Question 19 (1 point) The DuPont identity breaks down return on equit.pdf
 
Prepare a 3-4 page, double-spaced paper (cite 3-4 reliable sources) .pdf
Prepare a 3-4 page, double-spaced paper (cite 3-4 reliable sources) .pdfPrepare a 3-4 page, double-spaced paper (cite 3-4 reliable sources) .pdf
Prepare a 3-4 page, double-spaced paper (cite 3-4 reliable sources) .pdf
 
Place all the characteristics of living organisms the answer box. Ch.pdf
Place all the characteristics of living organisms the answer box.  Ch.pdfPlace all the characteristics of living organisms the answer box.  Ch.pdf
Place all the characteristics of living organisms the answer box. Ch.pdf
 
LABELING ACTIVITY 2 (Rs 1-10) 10 10. 12. 13 14, 15 16 62 circulatory .pdf
LABELING ACTIVITY 2 (Rs 1-10) 10 10. 12. 13 14, 15 16 62 circulatory .pdfLABELING ACTIVITY 2 (Rs 1-10) 10 10. 12. 13 14, 15 16 62 circulatory .pdf
LABELING ACTIVITY 2 (Rs 1-10) 10 10. 12. 13 14, 15 16 62 circulatory .pdf
 
Of 10 fish in a pond 4 are tagged. If three fish are caught and not .pdf
Of 10 fish in a pond 4 are tagged. If three fish are caught and not .pdfOf 10 fish in a pond 4 are tagged. If three fish are caught and not .pdf
Of 10 fish in a pond 4 are tagged. If three fish are caught and not .pdf
 

Recently uploaded

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 

need help with this java lab please read below and follow the steps.pdf

  • 1. need help with this java lab: please read below and follow the steps! Copy and paste the code at the bottom into your ide and go from there, please do not write a whole new program! The purpose of this lab is to give you an opportunity to make use of a stack in the implementation of a backtracking algorithm. This problem is generally referred to as the N Queens problem. The gist of the problem is to create an algorithm which can position N queens on a chess board so none of the queens can attack any other queen. For those of you who may not be familiar with chess, the queen can move horizontally, vertically, and diagonally. In the generalized N Queens problem, N represents the number of rows and columns of the game board and the number of queens that must be placed on the board in safe positions. we will NOT be using recursion in any way to solve this problem. The basic strategy that we will employ to solve this problem is to use backtracking. In this particular case, what backtracking means is that we will make a move that is safe for a queen at the time we make the move, but later on, we may discover that we are stuck and there is no safe move available for the next queen we are trying to place on the board, so we must backtrack. That means we will go back to the previous queen’s move, undo that move, and continue searching for another safe place to put that queen. We will use the stack to remember where we have placed queens on the board and when we need to back up, the queen at the top of the stack will be popped and we will use that queen’s position to resume the search for the next safe location.Stradegy below: There are N rows. When a queen is placed into a row, that row cannot be used by other queens. There are N columns. When a queen is placed into a column, that column cannot be used by other queens. There are 2 sets of diagonals to be concerned with, diagonals running upper left to lower right and diagonals running upper right to lower left. There is a simple mathematical relationship between N and the number of diagonals in each direction. When a queen is placed onto the board, one left to right diagonal is no longer safe for other queens, and one right to left diagonal is no longer safe for other queens. Our approach to placing the queens on the board will be to use nested loops. As an example the outer loop will be in control of which column we are currently searching for a spot to place a queen. So, the first queen we place will be in column 0, and when the outer loop has completed we will have placed N queens on the board, one in each column. The inner loop will iterate through the rows, from 0 to N-1 until it finds a row R such that row R is not taken by another queen, AND the 2 diagonals which intersect row R and the current column are not taken by another queen. IF we find such a safe location, we push the current row,
  • 2. column value onto a stack. Note: we can use the Java Point class to store the row and column numbers in the x, y values of a Point object. By placing a queen’s location information into the stack, we have affected the state of the board. We must update the state information to reflect that a row is no longer safe for other queens. We also must update the state of the two diagonals which intersect with the queen’s row, column position to indicate that those diagonals are no longer available to other queens to be placed later. After updating the state information, we can break out of the inner loop and continue on to the next column in the outer loop. The backtracking aspect of this exercise occurs when the inner loop fails to find a spot to place a queen in the current column. Inside the inner loop, we need to recognize that we have checked position (row N-1, current column) and found that it is not safe. Therefore there is no safe place for a queen in this column. Since we are stuck, we need to back up and try a different placement for the previously placed queen. To backtrack, we need to undo the actions taken when we placed the last queen onto the stack. That means pop the last queen off the stack, mark the row and diagonals associated with that queen’s position as available again, and reset the row and column loop control variables back to the point where they were when this queen was pushed onto the stack (ie row = poppedPoint.x, column = poppedPoint.y). After backtracking the row loop will continue to the next row to check if that row, column position is safe. I am providing you with a partially completed Java FX project for this project. The project I am giving you contains 2 classes. The GameBoard class provides methods for creation of the game board based on the size given to its constructor. It also provides methods for placing and removing a queen from a specific row, column position on the game board. The JavaFxQueens class is the main application class. It determines what size the game board is to be, creates an GameBoard object, and places the game board into a scene on the stage. It also starts up a thread which will find safe places on the board for all the queens. The placeQueens method in the JavaFxQueens class has not been completed. You must write the code needed to find safe locations for all the queens. Whenever you find a safe place and push a row, col position onto the stack, you must also call the placeQueen method on the GameBoard object to draw that queen on the board. Whenever you backtrack and pop a row, col position off the stack, you must also call the removeQueen method on the GameBoard object to remove that queen from the game board display. Note, that after calling either one of these 2 methods, you must call the delay method (which is provided) to slow down the rate at which moves are drawn on the board so that every queen placed or removed is visible on the display for a reasonable amount of time. Think very carefully about how you want to organize the data which captures the state of the game board (rows, diagonals). You do not need an actual representation of the game board (ie. no 2 dimensional array). Also think carefully about how to mathematically capture the
  • 3. relationship between a row, column position and which diagonals intersect that position. Part of creating efficient programs is designing clever data representations which can be accessed in very efficient ways from known information. here is the code: please copy the java queens class and the gameboard class into your ide and read the above to solve. ****javaQueens**** package javafxqueens; import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; import javax.swing.JOptionPane; /** * * @author RVolkers */ public class JavaFxQueens extends Application implements Runnable { private GameBoard board; private int boardSize = 0; @Override public void start(Stage primaryStage) { // Get the size of the game board from the user. Must be at least 5. while(boardSize < 5) { boardSize = Integer.parseInt(JOptionPane.showInputDialog("Enter size of chess board.")); } board = new GameBoard(boardSize); // The game board calculates how much display area it will need to display properly Scene scene = new Scene(board, board.getDisplaySize(), board.getDisplaySize()); primaryStage.setTitle("N Queens"); primaryStage.setScene(scene); primaryStage.show(); // Since the main thread is responsible for doing all the GUI updating, // we need a separate thread to process the placement of queens. That thread
  • 4. // will call methods on the GameBoard to tell the main thread where to place // or remove queens on the board. Thread thread = new Thread(this); thread.start(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } // Must do the main processing in a separate thread, so this class // implements the Runnable interface. @Override public void run() { // This thread calls a private method to figure out where the queens go placeQueens(); } // Used to slow down moves to enable seeing the board placement change // as each queen is placed or removed from the board private void delay() { try { Thread.sleep(500); } catch(InterruptedException e) { } } // Figure out where to place the queens here.... // Call placeQueen and removeQueen methods on the gameBoard object when needed private void placeQueens() { //insert new code here!
  • 5. } } ******gameboard****** package javafxqueens; import javafx.application.Platform; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.image.ImageView; import javafx.scene.layout.GridPane; /** * * @author RVolkers */ public class GameBoard extends GridPane { private final int ButtonSize = 110; private final int GapSize = 5; private int size; private Button[][] board; public GameBoard() { super(); setHgap(GapSize); setVgap(GapSize); setAlignment(Pos.CENTER); setPadding(new Insets(GapSize, GapSize, GapSize, GapSize)); size = 8; createBoard(); } public GameBoard(int n) { super(); setHgap(GapSize); setVgap(GapSize); setAlignment(Pos.CENTER); setPadding(new Insets(GapSize, GapSize, GapSize, GapSize)); size = n;
  • 6. createBoard(); } private void createBoard() { // Create an array to hold references to all the buttons on the board. board = new Button[size][size]; for (int row = 0; row < size; row++) { for (int col = 0; col < size; col++) { // Create each button with alternating colors Button b = new Button(); b.setPrefSize(ButtonSize, ButtonSize); if ((row + col) % 2 == 0) { b.setStyle("-fx-background-color: red"); } else { b.setStyle("-fx-background-color: black"); } // Add the button to the board and to the GridPane board[row][col] = b; add(b, col, row); } } } // Calculate the size of the display based on the size // of the buttons and the size of the gaps between buttons. public double getDisplaySize() { return size * ButtonSize + (size + 1) * GapSize; } // Verify that the row and col parameters are valid. // Pass a runnable object to the main thread to update the GUI // by adding the queen graphic to the appropriate button on the board public void placeQueen(int row, int col) throws IllegalArgumentException { if (row < 0 || row >= size || col < 0 || col >= size) { throw new IllegalArgumentException("Row or column out of bounds"); } Platform.runLater(() -> { board[row][col].setGraphic(new ImageView("queen.gif")); });
  • 7. } // Verify that the row and col parameters are valid. // Pass a runnable object to the main thread to update the GUI // by removing the queen graphic from the appropriate button on the board public void removeQueen(int row, int col) throws IllegalArgumentException { if (row < 0 || row >= size || col < 0 || col >= size) { throw new IllegalArgumentException("Row or column out of bounds"); } Platform.runLater(() -> { board[row][col].setGraphic(null); }); } } Solution i add some methods for display the queens as Q and move the queens import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; import javax.swing.JOptionPane; public class JavaFxQueens extends Application implements Runnable { private GameBoard board; private int boardSize = 0; @Override public void start(Stage primaryStage) { // Get the size of the game board from the user. Must be at least 5. while(boardSize < 5) { boardSize = Integer.parseInt(JOptionPane.showInputDialog("Enter size of chess board.")); } board = new GameBoard(boardSize); // The game board calculates how much display area it will need to display properly
  • 8. Scene scene = new Scene(board, board.getDisplaySize(), board.getDisplaySize()); primaryStage.setTitle("N Queens"); primaryStage.setScene(scene); primaryStage.show(); // Since the main thread is responsible for doing all the GUI updating, // we need a separate thread to process the placement of queens. That thread // will call methods on the GameBoard to tell the main thread where to place // or remove queens on the board. Thread thread = new Thread(this); thread.start(); } public static void main(String[] args) { launch(args); } // Must do the main processing in a separate thread, so this class // implements the Runnable interface. @Override public void run() { // This thread calls a private method to figure out where the queens go placeQueens(); } // Used to slow down moves to enable seeing the board placement change // as each queen is placed or removed from the board private void delay() { try { Thread.sleep(500); } catch(InterruptedException e) { } } // Figure out where to place the queens here.... // Call placeQueen and removeQueen methods on the gameBoard object when needed
  • 9. //here we need on method for display the queens public void showQueens(int[] s) { int n = s.length; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (s[i] == j) { System.out.print("Q"); } else { System.out.print(""); } } System.out.println(); } System.out.println(); } public void placeQueens(int p, int n) { for (int c = 0; c < n; c++) { if (placeQueens(p, c)) { s[r] = c; if (r == n - 1) { printQueens(s); } else { placeQueens(p + 1, n); } } } } public void callplaceNqueens() { placeQueens(0, s.length); } } ******gameboard****** package javafxqueens; import javafx.application.Platform; import javafx.geometry.Insets;
  • 10. import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.image.ImageView; import javafx.scene.layout.GridPane; /** * * @author RVolkers */ public class GameBoard extends GridPane { private final int ButtonSize = 110; private final int GapSize = 5; private int size; private Button[][] board; public GameBoard() { super(); setHgap(GapSize); setVgap(GapSize); setAlignment(Pos.CENTER); setPadding(new Insets(GapSize, GapSize, GapSize, GapSize)); size = 8; createBoard(); } public GameBoard(int n) { super(); setHgap(GapSize); setVgap(GapSize); setAlignment(Pos.CENTER); setPadding(new Insets(GapSize, GapSize, GapSize, GapSize)); size = n; createBoard(); } private void createBoard() { // Create an array to hold references to all the buttons on the board. board = new Button[size][size]; for (int row = 0; row < size; row++) { for (int col = 0; col < size; col++) {
  • 11. // Create each button with alternating colors Button b = new Button(); b.setPrefSize(ButtonSize, ButtonSize); if ((row + col) % 2 == 0) { b.setStyle("-fx-background-color: red"); } else { b.setStyle("-fx-background-color: black"); } // Add the button to the board and to the GridPane board[row][col] = b; add(b, col, row); } } } // Calculate the size of the display based on the size // of the buttons and the size of the gaps between buttons. public double getDisplaySize() { return size * ButtonSize + (size + 1) * GapSize; } // Verify that the row and col parameters are valid. // Pass a runnable object to the main thread to update the GUI // by adding the queen graphic to the appropriate button on the board public void placeQueen(int row, int col) throws IllegalArgumentException { if (row < 0 || row >= size || col < 0 || col >= size) { throw new IllegalArgumentException("Row or column out of bounds"); } Platform.runLater(() -> { board[row][col].setGraphic(new ImageView("queen.gif")); }); } // Verify that the row and col parameters are valid. // Pass a runnable object to the main thread to update the GUI // by removing the queen graphic from the appropriate button on the board public void removeQueen(int row, int col) throws IllegalArgumentException { if (row < 0 || row >= size || col < 0 || col >= size) { throw new IllegalArgumentException("Row or column out of bounds");