How to check diagonals in NQueens? - java

Im making the NQueens program in java but I am having trouble checking the diagonals. Right now I just go through the array in a way so it goes to the next diagonal spot but it is giving me out of bounds after going through the first possibility. Is there a different way to do this? Am i doing it wrong?
Here is the part that is giving me the array out of bounds exception
private boolean checkLowerDiag(int row, int col)
{
if(col == 0)
{
return false;
}
else
{
for(int i = row, j = col; i < myNumsQueen && j >= 0; i++, j--)
{
if(myBoard[i+1][j-1] == true) // this line is the out of bounds
{
return true;
}
}
return false;
}
}
Here is my entire code
package model;
public class NQueensModel
{
private int myNumsQueen;
public int myPossibilities=0;
private boolean[][] myBoard;
private static NQueensModel myModel = new NQueensModel(4);
public static void main (String[] args) {
System.out.println(myModel.solvePuzzle());
System.out.println(myModel.myPossibilities);
// System.out.println(myPossibilities);
}
public NQueensModel(int nQueens)
{
myNumsQueen = nQueens;
myPossibilities=0;
myBoard = new boolean[myNumsQueen][myNumsQueen];
}
public boolean solvePuzzle()
{
return this.solvePuzzle(0);
}
private boolean solvePuzzle(int ncolumn)
{
if(ncolumn>myNumsQueen-1)
{
myPossibilities++;
// return true;
}
int i;
for( i =0; i<myNumsQueen;i++)
{
if(this.isSafeMove(i, ncolumn)==true)
{
this.placeQueen(i,ncolumn);
System.out.println(i+ " " + ncolumn);
if(this.solvePuzzle(ncolumn+1)==true)
{
return true;
}
this.removeQueen(i, ncolumn);
System.out.println("remove: " + i+ " " + ncolumn);
}
}
return false;
}
private int solveCount(int count, int col)
{
for(int j = 0 ; j<col; j++){
if(myModel.solvePuzzle(j)==true){
count++;
}
else if(myModel.solvePuzzle(j)==false){
return count;
}
else
{
for(int i =0 ; i<col;i++){
count = solveCount(count, col+1);
}
return count;
}
return count;
}
return count;
}
private boolean isSafeMove(int row, int col)
{
if(this.checkLowerDiag(row, col)==true ||this.checkUpperDiag(row, col)==true ||this.checkLeft(row,col)==true)
{
return false;
}
else
{
return true;
}
}
private boolean checkUpperDiag(int row, int col)
{
if(row==0)
{
return false;
}
else
{
for(int i=row, j = col; i>=0 && j>=0; i--, j--)
{
if(myBoard[i][j]==true)
{
return true;
}
}
return false;
}
}
private boolean checkLowerDiag(int row, int col)
{
if(col==0 )
{
return false;
}
else
{
for(int i = row, j = col; i<myNumsQueen && j>=0; i++, j--)
{
if(myBoard[i+1][j-1]==true)
{
return true;
}
}
return false;
}
}
private boolean checkLeft(int row, int col)
{
if(col==0)
{
return false;
}
else
{
for(int i = col; i>=0; i--)
{
if(myBoard[row][i]==true)
{
return true;
}
}
return false;
}
}
private boolean placeQueen(int row, int col)
{
myBoard[row][col] = true;
return true;
}
private boolean removeQueen(int row, int col)
{
myBoard[row][col] = false;
return false;
}
// public String toString()
// {
//
// }
}

Related

How can I avoid java.lang.ArrayIndexOutOfBoundsException when joining a Queue?

I'm working on a simple(?) exercise for my Data Structures class. It works fine right up until I have an element leave the queue then try to add another one on at which point I get the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10
at queueExercise.IntegerQueue.join(IntegerQueue.java:20)
at queueExercise.IntegerQueueTest.main(IntegerQueueTest.java:27)
My code is as follows:
Queue Constructor Class:
public class IntegerQueue {
private int[] queue;
private int front;
private int end;
private int noInQueue;
private int count;
private boolean full;
public IntegerQueue(int max) {
queue = new int[max];
front = end = 0;
full = false;
}
public void join(int newValue) {
if (isFull()==false) {
queue[end] = newValue;
count++;
if (end == queue.length) {
end = 0;
}
else {
end++;
}
}else
System.out.println("Error: Queue Full");
}
public int leave() {
if (isEmpty()==false) {
noInQueue = queue[front];
queue[front]=0;
front++;
if (front==queue.length) {
front = 0;
}
count--;
}
else {
System.out.println("Error: Queue Empty");
}
System.out.println("Leaving: "+noInQueue);
return noInQueue;
}
public boolean isEmpty() {
if (count == 0){
return true;
}
else
return false;
}
public boolean isFull() {
if (count >= queue.length) {
return true;
}
else
return false;
}
public void printQueue() {
if (!isEmpty()) {
System.out.println("Printing Queue");
int pos = front;
int i =0;
while(i<queue.length) {
System.out.println(queue[pos]);
pos++;
i++;
if (pos >=queue.length) {
pos = 0;
}
}
}
}
}
Test Class
public class IntegerQueueTest {
static IntegerQueue q = new IntegerQueue(10);
public static void main(String[] args) {
int j;
System.out.println("Creating Queue");
for (int i = 0; i <10; i++) {
j = (int)(Math.random()*100);
if (!q.isFull()) {
q.join(j);
System.out.println("Adding: "+j);
}
}
q.printQueue();
q.join(112);
q.leave();
q.leave();
q.leave();
q.printQueue();
q.join(112);
q.join(254);
q.printQueue();
}
}
The problem is in the join method and more precisely in the condition if (end == queue.length). All you have to do is change it to if (end == queue.length - 1).

Can I add elements to a java queue using array without defining the front and the rear? I am having trouble with this

I am having trouble using enqueue and dequeue functions. I want to add elements without defining the front and rear in my scope.
public class MyStaticQueue
{
private int items[] ;
private int noOfItems = 0;
private int maxItems;
public MyStaticQueue(int m)
{
this.maxItems = m;
this.items = new int[maxItems];
this.noOfItems = 0;
}
public boolean isEmpty()
{
if(noOfItems == 0)
{
return true;
}
else
{
return false;
}
}
public int first()
{
return items[0];
}
public void add(int item)
{
for (int i=0; i<items[maxItems]; i++)
{
if (items[i] == 0)
{
items[i] = item;
}
noOfItems++;
}
}
}

Implementing “Check” in a Chess Game

Hello I am new in Java and I have stuck. I am trying to make chess game, I made everything except check and checkmate method, and if you have any suggestions I will be happy to read them. Here is my work till now:
This is the board class where we play the game:
public class Board {
public static final int COLOR_WHITE = 1;
public static final int COLOR_BLACK = 2;
public static PlayingPiece[][] board;
private boolean isFirstMove;
private int color;
public Board() {
this.setBoard(new PlayingPiece[8][8]);
this.isFirstMove = true;
this.initializePieces();
}
// Initialize the chess pieces
public void initializePieces() {
for (int i = 0; i < 8; i++) {
board[1][i] = new Pawn(1, i, COLOR_WHITE);
}
for (int i = 0; i < 8; i++) {
board[6][i] = new Pawn(6, i, COLOR_BLACK);
}
board[0][0] = new Rook(0, 0, COLOR_WHITE);
board[0][7] = new Rook(0, 7, COLOR_WHITE);
board[7][0] = new Rook(7, 0, COLOR_BLACK);
board[7][7] = new Rook(7, 7, COLOR_BLACK);
board[0][1] = new Knight(0, 1, COLOR_WHITE);
board[0][6] = new Knight(0, 6, COLOR_WHITE);
board[7][1] = new Knight(7, 1, COLOR_BLACK);
board[7][6] = new Knight(7, 6, COLOR_BLACK);
board[0][2] = new Officer(0, 2, COLOR_WHITE);
board[0][5] = new Officer(0, 5, COLOR_WHITE);
board[7][2] = new Officer(7, 2, COLOR_BLACK);
board[7][5] = new Officer(7, 5, COLOR_BLACK);
board[0][3] = new Queen(3, 0, COLOR_WHITE);
board[0][4] = new King(4, 0, COLOR_WHITE);
board[7][3] = new Queen(7, 3, COLOR_BLACK);
board[7][4] = new King(7, 4, COLOR_BLACK);
this.printBoard();
}
public boolean play(int color, int fromX, int fromY, int toX, int toY) {
boolean isTrue = false;
// Check if this is the first turn and only white can move
if (isFirstMove && color == COLOR_WHITE) {
isTrue = true;
} else if (isFirstMove && color == COLOR_BLACK) {
return false;
}
// check if player plays 2 times in a raw and if you move the piece from
// current possition
if (color == this.color || (toX == fromX && toY == fromY)) {
return false;
}
isTrue = true;
if (isTrue == true) {
this.isFirstMove = false;
// Check if player plays with his own color
if (((board[fromX][fromY]).getColor() != color)) {
return false;
}
// Check the isLegal movement of every chess piece
if ((board[fromX][fromY]).move(toX, toY)) {
board[toX][toY] = board[fromX][fromY];
board[fromX][fromY] = null;
}
this.printBoard();
}
return isTrue;
}
public PlayingPiece[][] getBoard() {
return board;
}
public void setBoard(PlayingPiece[][] board) {
Board.board = board;
}
This is the Pieces class with all kind of pieces:
package com.chess.www;
public class PlayingPiece {
public static final int COLOR_WHITE = 1;
public static final int COLOR_BLACK = 2;
public static final char BLACK_PAWN = '\u265F';
public static final char BLACK_ROOK = '\u265C';
public static final char BLACK_KNIGHT = '\u265E';
public static final char BLACK_BISHOP = '\u265D';
public static final char BLACK_QUEEN = '\u265B';
public static final char BLACK_KING = '\u265A';
public static final char WHITE_PAWN = '\u2659';
public static final char WHITE_ROOK = '\u2656';
public static final char WHITE_KNIGHT = '\u2658';
public static final char WHITE_BISHOP = '\u2657';
public static final char WHITE_QUEEN = '\u2655';
public static final char WHITE_KING = '\u2654';
public static final char NO_PIECE = ' ';
private int x, y;
private boolean isAlive;
private int color;
private char symbol;
protected PlayingPiece (int newX, int newY, int newColor) {
this.setX(newX);
this.setY(newY);
this.color = newColor;
this.isAlive = true;
}
protected PlayingPiece(int newX, int newY) {
this.setX(newX);
this.setY(newY);
}
protected PlayingPiece() {
}
public int getX() {
return x;
}
public void setY(int y) {
this.y = y;
}
public int getY() {
return y;
}
public void setX(int x) {
this.x = x;
}
protected boolean moveIsLegal (int newX, int newY) {
boolean isLegal = false;
if ((0 <= newX && newX <= 7) && (0 <= newY && newY <= 7)){
isLegal = true;
}
return isLegal;
}
public boolean move (int newX, int newY) {
if (moveIsLegal(newX, newY)) {
setX(newX);
setY(newY);
return true;
}
return false;
}
public int getColor() {
return color;
}
public boolean isAlive() {
return isAlive;
}
public void setAlive(boolean isAlive) {
this.isAlive = isAlive;
}
public char getSymbol() {
return symbol;
}
public void setSymbol(char symbol) {
this.symbol = symbol;
}
}
And here is the King class:
package com.chess.www;
public class King extends PlayingPiece {
public King(int newX, int newY, int color) {
super(newX, newY, color);
if (color == COLOR_BLACK) {
this.setSymbol(BLACK_KING);
} else {
this.setSymbol(WHITE_KING);
}
}
#Override
protected boolean moveIsLegal(int newX, int newY) {
int newPositionX = newX - getX();
int newPositionY = newY - getY();
int checkX = this.getX();
int checkY = this.getY();
if (super.moveIsLegal(newX, newY)) {
if ((Math.abs(newPositionX) == 1) && (newY == getY())) {
while (checkX != newX) {
if (this.isValidTraceX(checkX, newY, newX)) {
return true;
}
if (checkX > newX) {
checkX--;
} else if (this.getX() < newX) {
checkX++;
}
}
} else if ((newX == getX()) && (Math.abs(newPositionY) == 1)) {
while (checkY != newY) {
if (this.isValidTraceY(newX, checkY, newY)) {
return true;
}
if (checkY > newY) {
checkY--;
} else if (this.getY() < newY) {
checkY++;
}
}
} else if ((Math.abs(newPositionY) == 1) == (Math.abs(newPositionX) == 1)) {
while (checkX != newX && checkY != newY) {
if (this.isValidTrace(checkX, checkY, newX, newY)) {
return true;
}
if (checkX > newX) {
checkX--;
} else if (this.getX() < newX) {
checkX++;
}
if (checkY > newY) {
checkY--;
} else if (this.getY() < newY) {
checkY++;
}
}
}
}
return false;
}
public boolean isValidTraceX(int newX, int newY, int lastX) {
boolean isValid = true;
if ((Board.board[newX][newY]) != null) {
isValid = false;
}
if (((Board.board[lastX][newY]) != null)) {
if (Board.board[lastX][newY].getColor() == this.getColor()) {
isValid = false;
} else {
isValid = true;
}
}
return isValid;
}
public boolean isValidTraceY(int newX, int newY, int lastY) {
boolean isValid = true;
if ((Board.board[newX][newY]) != null) {
isValid = false;
}
if (((Board.board[newX][lastY]) != null)) {
if (Board.board[newX][lastY].getColor() == this.getColor()) {
isValid = false;
} else {
isValid = true;
}
}
return isValid;
}
public boolean isValidTrace(int newX, int newY, int lastX, int lastY) {
boolean isValid = true;
if ((Board.board[newX][newY]) != null) {
isValid = false;
}
if (((Board.board[lastX][lastY]) != null)) {
if (Board.board[lastX][lastY].getColor() == this.getColor()) {
isValid = false;
} else {
isValid = true;
}
}
return isValid;
}
}
I want to implement the method for check in board class do you have any suggestions?
The way I would implement would be just a method in the King class called something like, isChecked.
boolean isChecked() {
/* Check straight lines */
for (directions) { // up, down, left and right
for (square in direction) { // square by square from the king and out in the current direction
if (square contains opponent rook or queen)
return true;
else if (square contains friendly piece)
continue;
/* Check diagonals */
for (directions) { // left-up, left-down, right-up and right-down
for (square in direction) { // square by square from the king and out in the current direction
if (square contains opponent bishop or queen)
return true;
else if (square contains friendly piece)
continue;
/* Check pawns */
if (squares where pawns would threaten the king contains pawns)
return true;
/* Check king, this is to find if a square is legal to move to only */
if (squares where a king would threaten the king contains king)
return true;
/* Check knights */
if (squares where knights would threaten the king contains knights)
return true;
Sorry, I haven't really got time to write the entire code now, but the pseudo code should be enough to understand the concept. If you need I could fix it later today.
The principle is just, check every possible way a king can be checked.
If a king is checked and all possible moves are also checked, it is a checkmate.
Hope it helps :)
import java.util.Arrays;
public class KingsChecker {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
String[][] chess = new String[n][n];
print(chess,n);
}
public static void print (String[][] chess,int n) {
for(int i = 0; i< chess.length; i++) {
double random = Math.random()*n; //to generate a random number.
for(int j = 0; j < chess[i].length; j++) {
int column = (int)random;
int[] count = new int[n];
chess[i][j]= "+";
count[column]++;
if (count[column]<=1){
chess[i][column]="k";
System.out.print(chess[i][j]);
}
}
System.out.println();
}
}
}

mostFrequent method bags adt(abstract data types)

I am trying to implement a method named mostFrequent in a bag that finds the most frequent object in a bag For example, if B = {Bob, Joe, Bob, Ned, Bob, Bob}, then the method
returns Bob. Hint: The method is O(n^2).
public E MostFrequent (Bag<E> B){
// implementation here
}
The adt of the bag is the following:
package edu.uprm.ece.icom4035.bag;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class StaticBag implements Bag {
private int currentSize;
private Object elements[];
private class BagIterator implements Iterator {
private int currentPosition;
public BagIterator(){
this.currentPosition = 0;
}
#Override
public boolean hasNext() {
return this.currentPosition < currentSize;
}
#Override
public Object next() {
if (hasNext()){
return elements[this.currentPosition++];
}
else {
throw new NoSuchElementException();
}
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
}
public StaticBag(int maxSize){
if (maxSize < 1){
throw new IllegalArgumentException("Max size must be at least 1.");
}
this.currentSize = 0;
this.elements = new Object[maxSize];
}
#Override
public void add(Object obj) {
if (obj == null){
throw new IllegalArgumentException("Value cannot be null.");
}
else if (this.size() == this.elements.length){
throw new IllegalStateException("Bag is full.");
}
else {
this.elements[this.currentSize++] = obj;
}
}
#Override
public boolean erase(Object obj) {
int target = -1;
for (int i=0; i < this.size(); ++i){
if (this.elements[i].equals(obj)){
target = i;
break;
}
}
if (target == -1){
return false;
}
else {
this.elements[target] = this.elements[this.currentSize-1];
this.elements[this.currentSize-1] = null;
this.currentSize--;
return true;
}
}
#Override
public int eraseAll(Object obj) {
int copies = 0;
while(this.erase(obj)){
copies++;
}
return copies;
}
#Override
public int count(Object obj) {
int counter = 0;
for (int i=0; i < this.size(); ++i){
if (elements[i].equals(obj)){
counter++;
}
}
return counter;
}
#Override
public void clear() {
for (int i=0; i < this.size(); ++i){
this.elements[i] = null;
}
this.currentSize = 0;
}
#Override
public boolean isEmpty() {
return this.size() == 0;
}
#Override
public int size() {
return this.currentSize;
}
#Override
public boolean isMember(Object obj) {
return this.count(obj) > 0;
}
#Override
public Iterator iterator() {
return new BagIterator();
}
}
the method must be implemented in the most efficient way and if possible using the methods already given in the bag adt
What I've been trying is the following:
public E MostFrequent(Bag<E> B){
for(E e : B){
int counter = B.count(e)
}
}
but I don't seem to think of a way to return the object with more frequencies inside the loop

Problem Adding incremented class member variable to arraylist inside loop

Trying to add an incremented class member variable 'nNodeIndex' to arraylist, but at the end of the loop all the values stored are identical to the last iteration increment??
Class with member variable:
import java.util.ArrayList;
public class Graph {
private static ArrayList<GraphNode> Nodes = new ArrayList<GraphNode>();
private static ArrayList<GraphEdge> Edges = new ArrayList<GraphEdge>();
private static boolean diGraph;
private static int nNodeIndex;
private boolean uniqueEdge(int from, int to)
{
for(int i=0; i< Edges.size(); i++){
if(Edges.get(i).from() == from && Edges.get(i).to() == to)
return false;
}
return true;
}
private void removeInvalidEdges(int nodeIndex)
{
for(int i=0; i<Edges.size(); i++)
{
if(Edges.get(i).from() == nodeIndex)
Edges.remove(i);
if(Edges.get(i).to() == nodeIndex)
Edges.remove(i);
}
}
Graph(boolean directionalGraph)
{
diGraph = directionalGraph;
nNodeIndex = 1;
}
public GraphNode getNode(int nodeIndex)
{
return Nodes.get(nodeIndex);
}
public int getIndexByVector(int x, int y)
{
for(int i=0; i<Nodes.size(); i++)
{
if(Nodes.get(i).x() == x && Nodes.get(i).y() == y)
return i;
}
return -1;
}
public int nextFreeNodeIndex(){ return nNodeIndex; }
public void addNode(GraphNode node)
{
if(Nodes.size() > 0)
Nodes.add(node.index()-1, node);
else
Nodes.add(node);
nNodeIndex++;
}
public void removeNode(int index)
{
Nodes.get(index).setIndex(-1);
removeInvalidEdges(index);
}
public void addEdge(GraphEdge edge)
{
if(uniqueEdge(edge.from(), edge.to()))
Edges.add(edge);
if(!diGraph)
{
if(uniqueEdge(edge.to(), edge.from()))
Edges.add(new GraphEdge(edge.to(), edge.from()));
}
}
public void removeEdge(GraphEdge edge)
{
for(int i=0; i<Edges.size(); i++)
if(Edges.get(i).from() == edge.from() &&
Edges.get(i).to() == edge.to())
{
Edges.remove(i);
}
}
public int totalNodes(){ return Nodes.size(); }
public int totalEdges(){ return Edges.size(); }
public int nActiveNodes()
{
int count = 0;
for(int i=0; i<Nodes.size(); i++)
{
if(Nodes.get(i).index() != -1 )
count++;
}
return count;
}
public void reset()
{
nNodeIndex = 1;
Nodes.clear();
Edges.clear();
}
}
Use within main class:
for(int row = 1; row <= boardWidth; row++){
for(int col = 1; col <= boardHeight; col++){
graph.addNode(new GraphNode(graph.nextFreeNodeIndex(), row, col));
}
}
Graph Node class:
public class GraphNode extends Square {
private static int indexNum;
GraphNode(int n, int x, int y)
{
super(x,y);
indexNum = n;
}
public int index(){ return indexNum; }
public void setIndex(int index){ indexNum = index; }
}
Do you need to show us the GraphNode class? I wonder if the node index held by it (set by the first parameter passed in its constructor) is a static variable.

Categories