Unsure about the logic of the code - java

I cant test my method's code manually yet as Im not done with other associated code yet, but I feel like the logic of the method public boolean isFilledAt(int row, int col) is wrong. The method returns true if the shape has a filled block (any char) at the given row/col position and false if the block is empty(the dot '.'). If the position is out of bounds, raise a FitItException with an informative message. Could smb please look through it and let me know if anything is wrong with the method's code? Thanks!
public class CreateShape {
private int height;
private int width;
private char dc;
private Rotation initialPos;
private char[][] shape = new char[height][width];
public boolean isFilledAt(int row, int col)
{
if(row < 0 || row >= height || col < 0 || col >= width)
throw new FitItException("Oops! Out of bounds!");
else
{
for (int i = 0; i < shape.length; i++)
for (int j = 0; j < shape[i].length; j++) {
if (shape[row][col] == dc)
return true;
}
}
return false;
}

public boolean isFilledAt(int row, int col) {
if(row < 0 || row >= height || col < 0 || col >= width)
throw new FitItException("Oops! Out of bounds!");
else
return (shape[row][col] == dc);
}
does the same as your code currently does. I'm not sure what you are going through the array for, you're not even using the i and j variables.

Related

Fill a Matrix (2d array) recursively in Java

I have a Java programming assignment to do and in one of the questions, I have to fill a boolean 2d array (matrix) with "false" everywhere. I did it using two loops as following:
// The length and width are given
boolean [][] matrix;
matrix = new boolean [length][width];
int row;
int col;
for (row = 0; row < length; row++)
{
for (col = 0; col < width; col++)
{
matrix[row][col] = false;
}
}
The thing is that we just started the recursion chapter, and I would like if there is a way to do the same thing but this time using only recursion...
Thank you!
You can mimic the nested loop structure with recursion:
public static void fillWithFalse(boolean[][] array, int row) {
if (row < array.length) {
fillWithFalse(array[row], 0);
fillWithFalse(array, row + 1);
}
}
public static void fillWithFalse(boolean[] array, int col) {
if (col < array.length) {
array[col] = false;
fillWithFalse(array, col + 1);
}
}
or
public static void fillWithFalse(boolean[][] array, int row, int col) {
if (row < array.length) {
if (col < array[row].length) {
array[row][col] = false;
fillWithFalse(array, row, col + 1);
} else {
fillWithFalse(array, row + 1, 0);
}
}
}
Which is identical logic. But recursion is not good for this kind of thing and also to fill an array with false the correct solution is this:
boolean[][] matrix = new boolean[length][width];
Because boolean arrays will be default initialized with all elements as false. If the assignment is literally to fill a boolean array with false it may be basically a trick question because no action is necessary except to instantiate the array.
Well, not sure why is it necessary.. but.. here's my solution:
public static void insertFalse(boolean [][] arr,int row,int column)
{
if(row == 0&&column==0)
return ;
arr[row][column] = false;
if(column == 0)
insertFalse(arr,row-1,arr[0].length-1);
else
insertFalse(arr, row, column-1);
}

8 Non-Attacking Queens Algorithm with Recursion

I'm having trouble coding the 8 queens problem. I've coded a class to help me solve it, but for some reason, I'm doing something wrong. I kind of understand what's supposed to happen.
Also, we have to use recursion to solve it but I have no clue how to use the backtracking I've read about, so I just used it in the methods checking if a position is legitimate.
My board is String [] [] board = { { "O", "O"... etc etc with 8 rows and 8 columns.
If I'm getting anything wrong conceptually or making a grave Java mistake, please say so :D
Thanks!
public void solve () {
int Queens = NUM_Queens - 1;
while (Queens > 0) {
for (int col = 0; col < 8; col++) {
int row = -1;
boolean c = false;
while (c = false && row < 8) {
row ++;
c = checkPos (row, col);
}
if (c == true) {
board[row][col] = "Q";
Queens--;
}
else
System.out.println("Error");
}
}
printBoard ();
}
// printing the board
public void printBoard () {
String ret = "";
for (int i = 0; i < 8; i++) {
for (int a = 0; a < 8; a++)
ret += (board[i][a] + ", ");
ret += ("\n");
}
System.out.print (ret);
}
// checking if a position is a legitimate location to put a Queen
public boolean checkPos (int y, int x) {
boolean r = true, d = true, u = true, co = true;
r = checkPosR (y, 0);
co = checkPosC (0, x);
int col = x;
int row = y;
while (row != 0 && col != 0 ) { //setting up to check diagonally downwards
row--;
col--;
}
d = checkPosDD (row, col);
col = x;
row = y;
while (row != 7 && col != 0 ) { //setting up to check diagonally upwards
row++;
col--;
}
d = checkPosDU (row, col);
if (r = true && d = true && u = true && co = true)
return true;
else
return false;
}
// checking the row
public boolean checkPosR (int y, int x) {
if (board[y][x].contentEquals("Q"))
return false;
else if (board[y][x].contentEquals("O") && x == 7)
return true;
else //if (board[y][x].contentEquals("O"))
return checkPosR (y, x+1);
}
// checking the column
public boolean checkPosC (int y, int x) {
if (board[y][x].contentEquals("Q"))
return false;
else if (board[y][x].contentEquals("O") && y == 7)
return true;
else //if (board[y][x].contentEquals("O"))
return checkPosR (y+1, x);
}
// checking the diagonals from top left to bottom right
public boolean checkPosDD (int y, int x) {
if (board[y][x].contentEquals("Q"))
return false;
else if (board[y][x].contentEquals("O") && (x == 7 || y == 7))
return true;
else //if (board[y][x].contentEquals("O"))
return checkPosR (y+1, x+1);
}
// checking the diagonals from bottom left to up right
public boolean checkPosDU (int y, int x) {
if (board[y][x].contentEquals("Q"))
return false;
else if (board[y][x].contentEquals("O") && (x == 7 || y == 0))
return true;
else //if (board[y][x].contentEquals("O"))
return checkPosR (y-1, x+1);
}
}
As this is homework, the solution, but not in code.
Try to write a method that only handles what needs to happen on a single column; this is where you are supposed to use recursion. Do backtracking by checking if a solution exists, if not, undo your last change (i.e. change the queen position) and try again. If you only focus on one part of the problem (one column), this is much easier than thinking about all columns at the same time.
And as Quetzalcoatl points out, you are assigning false to your variable in the first loop. You probably do not want to do that. You should always enable all warnings in your compiler (run javac with -Xlint) and fix them.
You are trying some kind of brute-force, but, as you already mentioned, you have no recursion.
Your programs tries to put a queen on the first possible position. But at the end no solution is found. It follows that your first assumption (the position of your first queen) is invalid. You have to go back to this state. And have to assume that your checkPos(x,y) is false instead of true.
Now some hints:
As mentioned before by NPE int[N] queens is more suitable representation.
sum(queens) have to be 0+1+2+3+4+5+6+7=28, since a position has to be unique.
Instead of checking only the position of the new queen, you may check a whole situation. It is valid if for all (i,j) \in N^2 with queen(i) = j, there exists no (k,l) != (i,j) with abs(k-i) == abs(l-j)

Java Bishop Chess Board

Im working on figuring out the maximum number of bishops I can place on a nxn board without them being able to attack each other. Im having trouble checking the Diagonals. below is my method to check the diagonals. The squares where a bishop currently is are marked as true so the method is supposed to check the diagonals and if it returns true then the method to place the bishops will move to the next row.
Im not quite sure whats going wrong, any help would be appreciated.
private boolean bishopAttack(int row, int column)
{
int a,b,c;
for(a = 1; a <= column; a++)
{
if(row<a)
{
break;
}
if(board[row-a][column-a])
{
return true;
}
}
for(b = 1; b <= column; b++)
{
if(row<b)
{
break;
}
if(board[row+b][column-b])
{
return true;
}
}
for(c = 1; b <= column; b++)
{
if(row<c)
{
break;
}
if(board[row+c][column+c])
{
return true;
}
}
return false;
}
for(c = 1; b <= column; b++)
Shouldn't it be
for(c = 1; c <= column; c++)
By the way:
1) Use i, j, k instead of a, b, c, etc. No REAL reason why... it's just convention.
2) You don't have to keep naming new variables. Try something like this:
for(int i = 1; i <= column; i++)
{
...
}
//because i was declared in the for loop, after the } it no longer exists and we can redeclare and reuse it
for(int i = 1; i <= column; i++)
{
...
}
3) Your error checking is incorrect. It should be something like this:
for(int i = 1; i < 8; i++)
{
int newrow = row - i;
int newcolumn = column - i;
if (newrow < 0 || newrow > 7 || newcolumn < 0 || newcolumn > 7)
{
break;
}
if (board[newrow][newcolumn])
{
return true;
}
}
Now when you copy+paste your for loop, you only have to change how newrow and newcolumn are calculated, and everything else (including loop variable name) will be identical. The less you have to edit when copy+pasting, the better. We also attempt all 7 squares so we don't have to change the ending condition - the if check within the loop will stop us if we attempt to go out of bounds in ANY direction.
4) Better still, of course, would be using the for loop only once and passing only the changing thing into it... something like...
private boolean bishopAttackOneDirection(int rowdelta, int coldelta, int row, int column)
{
for(int i = 1; i < 8; i++)
{
int newrow = row + rowdelta*i;
int newcolumn = column + columndelta*i;
if (newrow < 0 || newrow > 7 || newcolumn < 0 || newcolumn > 7)
{
break;
}
if (board[newrow][newcolumn])
{
return true;
}
}
return false;
}
private boolean BishopAttack(int row, int column)
{
return BishopAttackInOneDirection(-1, -1, row, column)
|| BishopAttackInOneDirection(1, -1, row, column)
|| BishopAttackInOneDirection(1, 1, row, column)
|| BishopAttackInOneDirection(-1, 1, row, column);
}
Probably not quite the expected answer, but there is no reason to make life more complex then it is.
Im working on figuring out the maximum number of bishops I can place on a nxn board without them being able to attack each other.
public int getMaximumNumberOfNonAttackingBishopsForSquareBoardSize(final int boardSize) {
if (boardSize < 2 || boardSize > (Integer.MAX_VALUE / 2))
throw new IllegalArgumentException("Invalid boardSize, must be between 2 and " + Integer.MAX_VALUE / 2 + ", got: " + boardSize);
return 2 * boardSize - 2;
}
Source: http://mathworld.wolfram.com/BishopsProblem.html

strange IndexOutOfBound error

Hello I am writing a program for a programming class and I am getting a:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 18
at Life.countNeighbors(Life.java:200)
at Life.genNextGrid(Life.java:160)
I've gotten ArrayIndexOutOfBoundsException errors before, usually caused when I try to add or substract a index of an array. However this time it is quite different and I was hoping someone here can point out why the error is occuring.
info about my program: the program is like John Conway game of life. using a 2d array and then setting certain elements to (true = alive) or (false = dead) the program then determine if a cell lives or dies in the next generation base on the number of neighbors it has. (3 neighbors = birth of a new cell) (2,3 neighbor = they stay alive) anything else they died in the next generation.
The IndexOutOfBound error is caused by this line according to my editor:
if(!(grid[1][1]) && !(grid[1][18]) && !(grid[18][1]) && !(grid[18][18]))
I created the above line as a constraint, and it should not tell java to search a index beyond the bounds of the original array since they are merely booleans (true/false)statement in the end. If anyone can help me debug this error that would be splendid.
HERE IS MY CODE: (does not include main method)
public static void clearGrid ( boolean[][] grid )
{
int col;
int row = 1;
while(row < 18){
for(col = 1; col < 18; col++){
grid[row][col]= false;//set each row to false
}
row++;
}//set all elements in array to false
}
public static void genNextGrid ( boolean[][] grid )
{
//new tempprary grid
boolean[][] TempGrid = new boolean[GRIDSIZE][GRIDSIZE];
TempGrid= grid; // copy the current grid to a temporary grid
int row = 1;
int col = 1;
countNeighbors(TempGrid, row, col); // passes the TempGrid to countNieghbor method
for(row = 1; row < 18; row++){
countNeighbors(TempGrid, row, col);
for(col = 1; col < 18; col++){
countNeighbors(TempGrid, row, col);
if(countNeighbors(grid, row, col) == 3)
{
TempGrid[row][col] = true;
}
else if(countNeighbors(grid, row, col) == 2 || countNeighbors(grid, row, col) == 3)
{
TempGrid[row][col] = true;
}
else
{
TempGrid[row][col] = false;
}
}
}
}
public static int countNeighbors ( final boolean[][] grid, final int row, final int col )
{
int n = 0; //int used to store the # of neighbors
int temprow = row;
int tempcol = col;
//count # of neighbors for the cell on the edge but not the corner
for(temprow = row; temprow <= 18; temprow++)
{
for(tempcol = row; tempcol <= 18; tempcol++)
{
if(temprow == 1 || temprow == 18 || tempcol == 1 || tempcol ==18)
{
if(!(grid[1][1]) && !(grid[1][18]) && !(grid[18][1]) && !(grid[18][18]))
{
if(grid[temprow][tempcol] == true)
{
n++;
}
}
}
}
}
//count # of neighbors for the corner cells
for(temprow = row; temprow <= 18; temprow++)
{
for(tempcol = row; tempcol <= 18; tempcol++)
{
if(grid[1][1] || grid[1][18] || grid[18][1] || grid[18][18])
{
if(grid[temprow][tempcol] == true)
{
n++;
}
}
}
}
// count the cells that are not on the edge or corner
while(temprow >= 2 && tempcol >= 2 && temprow <= 17 && tempcol <= 17)
{
for(temprow = row; temprow-1 <= temprow+1; temprow++)
{
for(tempcol = col; tempcol-1 <= tempcol+1; tempcol++)
{
if(grid[temprow][tempcol] == true)
{
n++;
}
}
}
}
return n; // return the number of neighbors
}
Without a full stack trace and an indication as to where the problem lies, this is my best guess:
grid[18][1]
The value 18 is beyond the size of the array you can access, in Java arrays are zero based (0). Since I have seen 17 all throughout your post, this seems like the most logical reason why.
In Java, array indices are numbered from 0 to n-1. From looking at your code, it would appear that it assumes that they are numbered from 1 to n.

Recursive Searching in Java

So I've been writing a program for the game boggle. I create a little board for the user to use, but the problem is I don't know how to check if that word is on the board recursively. I want to be able to check if the word the entered is indeed on the board, and is valid. By valid I mean, the letters of the word must be adjacent to each other. For those who have played boggle you'll know what I mean. All I want to do is check if the word is on the board.
This is what I have so far ....
import java.io.*;
public class boggle {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
private String s = "";
private int [][] lettersNum = new int [5][5];
private char [][] letters = new char [5][5];
private char [] word = new char [45]; // Size at 45, because the longest word in the dictionary is only 45 letters long
private char [] temp;
public void generateNum()
{
for (int row = 0; row < 5; row ++)
{
for (int col = 0; col < 5; col++)
{
lettersNum [row][col] = (int) (Math.random() * 26 + 65);
}
}
}
public void numToChar()
{
for (int row = 0; row < 5; row ++)
{
for (int col = 0; col < 5; col++)
{
letters [row][col] = (char)(lettersNum[row][col]);
}
}
}
public void display()
{
for (int row = 0; row < 5; row ++)
{
for (int col = 0; col < 5; col++)
{
System.out.print(letters[row][col]);
}
System.out.println("");
}
}
public void getInput() throws IOException
{
System.out.println("Please enter a word : ");
s=br.readLine();
s=s.toUpperCase();
word = s.toCharArray();
}
public int search(int row, int col)
{
if((row <0) || (row >= 5) || (col < 0) || (col >= 5))
{
return (0);
}
else
{
temp = word;
return (1+ search(row +1, col) +
search(row -1, col) +
search(row, col + 1) +
search(row, col-1) +
search(row +1, col +1)+
search(row +1, col -1)+
search(row -1, col +1)+
search(row -1, col -1));
}
}
}
The search was my searching algorithm to check if the word is on the board but I don't know if it is correct or if it will work. Furthermore, I don't know how to actually tell the user that the word is valid !
Thanks for all the help :)
SO I tried to use what you suggested below but I dont really understand the int [5][5] thing. So this is what I tried, but I keep getting out of bounds errors ! Here is the soruce ...
public void locate()
{
temp = word[0];
for (int row = 0; row <5; row++)
{
for (int col = 0; col <5; col++)
{
if(temp == letters[row][col])
{
search(row,col);
}
}
}
}
public int search(int row, int col)
{
if(letters[row][col-1]==word[count]) // Checks the letter to the left
{
count++;
letters[row][col-1] = '-'; // Just to make sure the program doesn't go back on itself
return search(row, col-1);
}
else if (letters[row][col+1] == word[count])// Checks the letter to the right
{
count++;
letters[row][col+1] = '-';// Just to make sure the program doesn't go back on itself
return search(row, col +1);
}
else if (letters[row+1][col]== word[count])// Checks the letter below
{
count++;
letters[row+1][col] = '-';// Just to make sure the program doesn't go back on itself
return search(row +1 , col);
}
else if (letters[row-1][col]== word[count])// Checks the letter above
{
count++;
letters[row-1][col] = '-';// Just to make sure the program doesn't go back on itself
return search(row -1 , col);
}
else if (letters[row-1][col-1]== word[count])// Checks the letter to the top left
{
count++;
letters[row-1][col-1] = '-';// Just to make sure the program doesn't go back on itself
return search(row -1 , col-1);
}
else if (letters[row-1][col+1]== word[count])// Checks the letter to the top right
{
count++;
letters[row-1][col+1] = '-';// Just to make sure the program doesn't go back on itself
return search(row -1 , col+1);
}
else if (letters[row+1][col-1]== word[count])// Checks the letter to the bottom left
{
count++;
letters[row+1][col-1] = '-';// Just to make sure the program doesn't go back on itself
return search(row +1 , col-1);
}
else if (letters[row+1][col+1]== word[count])// Checks the letter to the bottom right
{
count++;
letters[row+1][col+1] = '-';// Just to make sure the program doesn't go back on itself
return search(row +1 , col+1);
}
return 0;
}
private int count = 0; (was declared at the top of the class, in case you were wondering where I got the word[count] from
Your current search function doesn't actually do anything. I'm assuming this is homework so, no free lunch ;)
The simplest approach would be to have two recursive functions:
public boolean findStart(String word, int x, int y)
This will do a linear search of the board looking for the first character in word. If your current location doesn't match, you call yourself with the next set of coords. When it finds a match, it calls your second recursive function using word, the current location, and a new, empty 4x4 matrix:
public boolean findWord(String word, int x, int y, int[][] visited)
This function first checks to see if the current location matches the first letter in word. If it does, it marks the current location in visited and loops through all the adjoining squares except ones marked in visited by calling itself with word.substring(1) and those coords. If you run out of letters in word, you've found it and return true. Note that if you're returning false, you need to remove the current location from visited.
You can do this with one function, but by splitting out the logic I personally think it becomes easier to manage in your head. The one downside is that it does do an extra comparison for each first letter in a word. To use a single function you would need to keep track of what "mode" you were in either with a boolean or a depth counter.
Edit: Your longest word should only be 16. Boggle uses a 4x4 board and a word can't use the same location twice. Not that this really matters, but it might for the assignment. Also note that I just did this in my head and don't know that I got it 100% right - comments appreciated.
Edit in response to comments:
Here's what your iterative locate would look like using the method I outline above:
public boolean locate(String word)
{
for (int row = 0; row < 4; row++)
{
for (int col =0; col < 4; col++)
{
if (word.charAt(0) == letters[row][col])
{
boolean found = findWord(word, row, col, new boolean[4][4]);
if (found)
return true;
}
}
}
return false;
}
The same thing recursively looks like the following, which should help:
public boolean findStart(String word, int x, int y)
{
boolean found = false;
if (word.charAt(0) == letters[x][y])
{
found = findWord(word, x, y, new boolean[4][4]);
}
if (found)
return true;
else
{
y++;
if (y > 3)
{
y = 0;
x++;
}
if (x > 3)
return false;
}
return findStart(word, x, y);
}
So here's findWord() and a helper method getAdjoining() to show you how this all works. Note that I changed the visited array to boolean just because it made sense:
public boolean findWord(String word, int x, int y, boolean[][] visited)
{
if (letters[x][y] == word.charAt(0))
{
if (word.length() == 1) // this is the last character in the word
return true;
else
{
visited[x][y] = true;
List<Point> adjoining = getAdjoining(x,y,visited);
for (Point p : adjoining)
{
boolean found = findWord(word.substring(1), p.x, p.y, visited);
if (found)
return true;
}
visited[x][y] = false;
}
}
return false;
}
public List<Point> getAdjoining(int x, int y, boolean[][] visited)
{
List<Point> adjoining = new LinkedList<Point>();
for (int x2 = x-1; x2 <= x+1; x2++)
{
for (int y2 = y-1; y2 <= y+1; y2++)
{
if (x2 < 0 || x2 > 3 ||
y2 < 0 || y2 > 3 ||
(x2 == x && y2 == y) ||
visited[x2][y2])
{
continue;
}
adjoining.add(new Point(x2,y2));
}
}
return adjoining;
}
So now, after you get input from the user as a String (word), you would just call:
boolean isOnBoard = findStart(word,0,0);
I did this in my head originally, then just went down that path to try and show you how it works. If I were to actually implement this I would do some things differently (mainly eliminating the double comparison of the first letter in the word, probably by combining the two into one method though you can do it by rearranging the logic in the current methods), but the above code does function and should help you better understand recursive searching.

Categories

Resources