How to change value of 2D bool array? - java

I have this assignment for school:
Imagine a chess board and an ant. The ant is randomly put on the
board and after that it can walk up, down, left and right (not diagonally). The ant cannot walk over the edge of the chess board
(if it tries, it is not counted as a movement). The task is to create
a program called Ants.java that simulates the walking over the
chess board of an ant. To walk to another square than the one
the ant is currently on is called a “step” (even though it will take
the ant several steps to move…). Each simulation should calculate the number of “steps” the ant takes to visit all squares on
the chess board. The simulations must be done ten times and
an average should be calculated at the end of the simulation.
An example run of the simulation is shown below:
Ants
Number of steps in simulation 1: 708
Number of steps in simulation 2: 818
Number of steps in simulation 3: 953
Number of steps in simulation 4: 523
Number of steps in simulation 5: 671
Number of steps in simulation 6: 338
Number of steps in simulation 7: 535
Number of steps in simulation 8: 702
I am quite sure that I'm about 95% done. However, I need an array to store bool values, to see if the ant has visited the square on the board or not. I can't really figure out how to do it. Ignore the "isVisited", it was my first idea.
This is my code right now:
public static void main(String[] args) {
// Sums every step in the 10 iterations
double totalNumber = 0;
boolean[][] grid = new boolean[8][8];
for (int r = 0; r< grid.length; r++)
{
for (int c = 0 ; c<grid[0].length; c++)
{
grid[r][c] = false;
}
}
// Just a loop to make the ant walk 10 times
for (int k = 1; k <= 10; k++) {
// Setting board to false, not visited
boolean isVisited = false;
// Creating spawn points
int x = (int) (Math.random() * (8 + 1)) + 1;
int y = (int) (Math.random() * (8 + 1)) + 1;
// Setting spawn point to
isVisited = true;
// Variables, steps, min coord and max coords
int count = 0;
int minY = 1;
int maxY = 8;
int minX = 1;
int maxX = 8;
// All the unchecked places
int unchecked = 64;
// Places where the ant has been
int alreadyChecked = 0;
// While there's more than 0 unchecked places, random 1 - 4
while (unchecked > 0) {
int random = (int) (Math.random() * 4 + 1);
// West
if (random == 1) {
// Move to the left
x--;
// If the ant falls off
if (x < minX) {
// Bump it back
x++;
}
// If the place is visited
if (isVisited) {
// Already checked
alreadyChecked++;
// Count step anyway
count++;
}
// If it's not
if(!isVisited) {
// Set to visited
isVisited = true;
// Remove 1 from the unchecked
unchecked--;
// And take a step
count++;
}
}
// East
if (random == 2) {
x++;
if (x > maxX) {
x--;
}
if (isVisited) {
alreadyChecked++;
count++;
}
if(!isVisited) {
isVisited = true;
unchecked--;
count++;
}
}
// North
if (random == 3) {
y++;
if (y > maxY) {
y--;
}
if (isVisited) {
alreadyChecked++;
count++;
}
if(!isVisited) {
isVisited = true;
unchecked--;
count++;
}
}
// South
if (random == 4) {
y--;
if (y < minY) {
y++;
}
if (isVisited) {
alreadyChecked++;
count++;
}
isVisited = true;
unchecked--;
count++;
}
}

/**
* This simulation assumes Ant movement is discrete relative to grid cells
* i.e. its either in one of these cells at a time, overlapping two cells in not allowed!!
* **/
public class AntMovementSimulation
{
int onBoard[][] = null;
int antPosX = 0;
int antPosY = 0;
int antPrevPosX = 0;
int antPrevPosY = 0;
int directionOfMovement = 0;
int stepsCount = 0;
AntMovementSimulation()
{
onBoard = new int[8][8];
//initialize each position in onBoard to -1 ,implying Ant has not been placed yet, not even once!!
for( int i = 0 ; i < 8 ; i++ )
{
for( int j = 0 ; j < 8 ; j++ )
{
onBoard[i][j] = -1;//implying Ant has not been placed yet, not even once!!
}
}
//place Ant in random cell
antPosX = (int)Math.round(Math.random()*7);//generating random number between 0 and 7, since index is from 0 to 7 as there are 8 cell!!
antPosY = (int)Math.round(Math.random()*7);
//assigning 1 to onBoard at index antPosX,antPosY to indicate Ant has been placed there
onBoard[antPosX][antPosY] = 1;
}
/*this function returns false if any cell has -1,else true
* cause when all cells have been traversed , each cell have non negative value,either 0 or 1
* */
public boolean areAllCellsTraversed()
{
boolean result = true;
for( int i = 0 ; i < 8 ; i++ )
{
for( int j = 0 ; j < 8 ; j++ )
{
if( onBoard[i][j] == -1 )//implying this cell not traversed yet,i.e Ant not placed in this cell yet!!
{
result = false;
}
}
}
return result;
}
public void simulate()
{
//loop while all cells have been not traversed
while( !areAllCellsTraversed() )
{
directionOfMovement = (int)Math.round(Math.random()*3);//generating random number between 0 and 3
switch( directionOfMovement )
{
case 0://move left-to-right
antPosX += 1;
if( antPosX >= 7 ) antPosX = 0; //since largest array index is 1 less than its size, we compare with 7 instead of 8
break;
case 1://move right-to-left
antPosX -= 1;
if( antPosX <= 0 ) antPosX = 7;
break;
case 2://move top-to-bottom
antPosY += 1;
if( antPosY >= 7 ) antPosY = 0;
break;
case 3://move bottom-to-top
antPosY -= 1;
if( antPosY <= 0 ) antPosY = 7;
break;
}
//assign 0 to previous position, meaning Ant is no longer there
onBoard[antPrevPosX][antPrevPosY] = 0;
//assign 1 to new position , meaning Ant is here
onBoard[antPosX][antPosY] = 1;
stepsCount++;
antPrevPosX = antPosX;
antPrevPosY = antPosY;
}
//once all cells have been traversed , print result!!
printSteps();
}
/*prints the total number of step taken to traverse all cells*/
public void printSteps()
{
System.out.println("Total steps taken by Ant to traverse all cells = "+stepsCount);
}
public static void main(String[] args)
{
int sumOfTotalNumOfSteps = 0;
AntMovementSimulation[] amsArray = new AntMovementSimulation[10];
for( AntMovementSimulation ams: amsArray )
{
ams = new AntMovementSimulation();
ams.simulate();
sumOfTotalNumOfSteps += ams.stepsCount;
}
System.out.println("Average num of steps taken by Ant to traverse all cells = "+ sumOfTotalNumOfSteps/10);
}
}

Related

How to find circumference and area of a 2D shape whose indices are given as 0 or 1 in a 2D array?

Given a 2D array of size 20x20 whose values resemble a 2D shape, for example a square or rectangle:
public static int[][] rectangle= {
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
};
I would like to find its circumference and area in an algorithm that does the following:
Finds the nearest (1) point starting from the center (point[10][10]).
Uses the nearest (1) point as a starting point to iterate over all the remaining 1s to count the
circumference.
calculates the number of zeros enclosed by the circumference to calculate the area
Now below is where I am currently at; the "guess" method calculates the nearest (1) point and executes the "count" method which then calculates the circumference.
public static void guess() {
boolean found = false;
if(!found) {
int y = 10;
for(int x = 10; x <= 20; x++) {
if(rectangle[x][y]==1) {
rectangle[x][y] = 2;
found = true;
break;
}else if(rectangle[x][y++]==1) {
rectangle[x][y] = 2;
found = true;
break;
}
}
}
if(!found) {
int y = 10;
for(int x = 10; x >= 0; x--) {
if(rectangle[x][y]==1) {
rectangle[x][y] = 2;
found = true;
break;
}else if(rectangle[x][y--]==1) {
rectangle[x][y] = 2;
found = true;
break;
}
}
}
if(!found) {
int x = 10;
for(int y = 10; y <= 20; y++) {
if(rectangle[x][y]==1) {
rectangle[x][y] = 2;
found = true;
break;
}else if(rectangle[x][y++]==1) {
rectangle[x][y] = 2;
found = true;
break;
}
}
}
if(!found) {
int x = 10;
for(int y = 10; y >= 0; y--) {
if(rectangle[x][y]==1) {
rectangle[x][y] = 2;
found = true;
break;
}else if(rectangle[x][y--]==1) {
rectangle[x][y] = 2;
found = true;
break;
}
}
}
for(int i = 0; i < 20; i++) {
for(int j = 0; j < 20; j++) {
if(rectangle[i][j] == 2) {
Count(i, j);
break;
}
}
}
}
public static void Count(int x, int y) {
public int circumf;
int tx = x;
int ty = y;
for(int c = 40; c >=0; c--) {
if((c/2)-1<0 || x>=20 || x<0 || y>=20 || y<0) break;
if(rectangle[x][(int) (c/2)-1]==1 || rectangle[(int) (c/2)-1][y]==1
|| rectangle[x++][y]==1 || rectangle[x][y++]==1
|| rectangle[x--][(int) (c/2)-1]==1 || rectangle[(int) (c/2)-1][y--]==1 || rectangle[x--][y]==1 || rectangle[x][y--]==1) {
circumf++;
}
}
x = tx;
y = ty;
for(int c = 0; c <=40; c++) {
if((c/2)>=20 || x>=20 || x<0 || y>=20 || y<0) break;
if(rectangle[x][(int) (c/2)]==1 || rectangle[(int) (c/2)][y]==1
|| rectangle[x++][y]==1 || rectangle[x][y++]==1
|| rectangle[x--][(int) (c/2)]==1 || rectangle[(int) (c/2)]
[y--]==1 || rectangle[x--][y]==1 || rectangle[x][y--]==1) {
circumf++;
}
}
System.out.print(circumf);
Now, the guess method calculates the nearest point correctly, however the count method doesn't correctly counts the circumference which is close to 70 in the above example.
As for the area calculating algorithm, I still didn't quite figure it out.
The above code isn't the most brilliant or organized thing I know, but any help would be really appreciated!
Suppose you find the nearest one at index [i][j]. You need to check the nearest values in a cross pattern since your object is a rectangle.
For example you are in the middle one in the left edge of the rectangle:
0 1 0
0 1 0
0 1 0
You check were the 1's "continue" finding thus the edge direction. There are 2 possible outcomes either
[x-1][y]=[x][y]=[x+1][y] or [x][y-1]=[x][y]=[x][y+1]==1
So,you found that the edge is vertical. Continue iterating through this verical line until the condition [x][y-1]==1 is false. Then do the same thing for the horizontal line.
Now for the 0's count you could store the index i,j of all the corners while you are doing the above check.If you know their positions and the size of the array is fixed you can calculate the 0's like:
0's area = [(DL_corner_index - 1) - (UL_corner_index + 1)] x [(UR_corner_index - 1) - (UL_corner_index + 1)]
int rectangle[10][10] ={
{0,0,0,0,0,0,0,0,0,0},
{0,1,1,1,1,1,1,1,1,0},
{0,1,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,1,0},
{0,1,1,1,1,1,1,1,1,0},
{0,0,0,0,0,0,0,0,0,0}
};
//calculating area of zeros with known corner coordinates
//you have stored the coordinates in variables like this
int UL_X=1,UR_X=8;
int UL_Y=1,DL_Y=8;
int area = ((UR_X-1) - UL_X)*((DL_Y-1)-UL_Y);
cout<<area; //36
}

Java: How to move a knight on a chessboard until no possible moves are left

I have an assignment to have a knight move around the chessboard until it either completes a full tour or has no where else to go.
im having a problem figuring out how to have it actually stop after there are no more moves. I have the algorithm for the movement down, as well as bounds checking on the chessboard.
setting the loop count to 64 just times out, because the program will try to continually find a spot that doesn't exist if a perfect tour isn't created.
two ideas I have had to fix this is to either increment a variable every time a certain position is checked around a certain spot, and if all possible moves are taken by a previous move, terminate the program. Problem is I have no idea how to actually do this.
A second idea I had is to have the program quit the for loop after 2 seconds(during which the for loop will check each position way more than once) but I feel like my professor would crucify me upside down if I did that
here is my code:
import apcslib.*; //this is only for Format()
public class ktour
{
int[][] kboard = new int[9][9];
int[] vert = new int[9];
int[] horiz = new int[9];
ktour()
{
vert[1] = -2;vert[2] = -1;vert[3] = 1;vert[4] = 2;vert[5] = 2;vert[6] = 1;vert[7] = -1;vert[8] = -2;
horiz[1] = 1;horiz[2] = 2;horiz[3] = 2;horiz[4] = 1;horiz[5] = -1;horiz[6] = -2;horiz[7] = -2;horiz[8] = -1;
path();
}
public void path()
{
int row = 1;
int col = 1;
int loops = 10; //i have this set to 10 for now
int col2 = 1;
int row2 = 1;
int r = (int)(Math.random() * (8) +1); //returns a random from 1 to 9
//System.out.println(r);
kboard[col][row] = 1;
for(int x = 2; x < loops; x++) //this runs the bounds check and places each number for the amount that loops is
{
r = (int)(Math.random() * (8) +1);
col = col2;
row = row2;
col = col + vert[r];
row = row + horiz[r];
while(col <= 0 || col > 8 || row <= 0 || row > 8) //bounds check, will keep running until both row and columb is in the board
{
r = (int)(Math.random() * (8) + 1);
col = col2;
row = row2;
col = col + vert[r];
row = row + horiz[r];
}
if(kboard[col][row] == 0)
{
kboard[col][row] = x;
row2 = row;
col2 = col;
}
else
{
x--; //if the above if is false and a number already occupies the generated spot, x is decremented and the program tries again
}
}
printboard();
}
public void printboard()
{
for(int y = 1; y < 9; y++)
{
System.out.println();
for(int x = 1; x < 9; x++)
{
System.out.print(Format.right(kboard[y][x],3));
}
}
}
}
I was able to fix my lab with the following code. I created a variable called count which I used to check if at any move there were no more moves left. As there are only 8 moves, when the variable reached 9 the code terminated, and printed up to the point it got to.
I had to put multiple if statements excluding r = math.random if count was not 0, meaning I was checking r 1-9, aka every possible move. Therefore, I couldn't use a randomizer, I had to traverse all 8 possible moves.
I also ran into problems when I reached the line where it checks if kboard[col][row] == 0. if you were running through a loop with count greater than 1, it was possible that col or row could be out of bounds, due to lack of a randomizer in the bounds checker. If left without a break, the bounds checker would run forever without a random number generated every time. I fixed this by adding an if statement that allowed the program to proceed if col and row were inside the board. if they were not, x was decremented and count was increased again, signifying a failed attempt.
This way I was able to check all possible moves, disregarding whether or not they were inside the board.
public void path()
{
int row = 1;
int col = 1;
int loops = 64; //i have this set to 10 for now
int col2 = 1;
int row2 = 1;
int count = 0;
boolean end = false;
int r = (int)(Math.random() * (8) +1); //returns a random from 1 to 9
//System.out.println(r);
kboard[col][row] = 1;
for(int x = 2; x < loops; x++) //this runs the bounds check and places each number for the amount that loops is
{
if(count == 0)
r = (int)(Math.random() * (8) +1);
if(count >= 1 && r != 8)
r++;
col = col2;
row = row2;
col = col + vert[r];
row = row + horiz[r];
while(col <= 0 || col > 8 || row <= 0 || row > 8) //bounds check, will keep running until both row and columb is in the board
{
if(count == 0)
r = (int)(Math.random() * (8) + 1);
col = col2;
row = row2;
col = col + vert[r];
row = row + horiz[r];
if(count >= 1)
break;
}
end = false;
if(r == 8 || r == 9)
r = 1;
if(count >= 9)
{
System.out.println("Halting... no where else to go");
loops = 0;
}
if(!(col <= 0 || row <= 0 || row > 8 || col > 8))
{
if(kboard[col][row] == 0)
{
kboard[col][row] = x;
row2 = row;
col2 = col;
count = 0;
}
else
{
count++;
x--; //if the above if is false and a number already occupies the generated spot, x is decremented and the program tries again
}
}
else
{
count++;
x--;
}
}
printboard();
}

Why is my Java Tortoise and Hare Race not displaying properly?

I have seen several questions about the Tortoise and Hare Race but they are all pertaining to applets and I am not programming an applet. The program is meant to I am having some trouble with the display output of my program. I would like to have the program display an output that looks something like this:
______T__________H________________________________
__________T_______________________H_______________
_____________T________H___________________________
etc. until either the tortoise or the hare reaches the end and wins the race. As of right now, my output looks like this:
______________________________HT__________________________________________________HT__________________________________________________HT_
over and over in what seems to be an infinite loop. Here is my code:
public class TortoiseAndHair {
public static void main ( String [] args )
{
int t = 0; // Keeps track of tortoise progress
int h = 0; // Keeps track of hare progress
System.out.println( "AND THEY'RE OFF!!" );
while (t < 50 || h < 50)
{
hareMove( h );
tortoiseMove( t );
if (t>1 && h> 1 && t == h) // Display when tortoise and hare occupy same space beyond start
{
System.out.print( "OUCH!!");
}
if ( t < 1 )
{ // Prevents tortoise from slipping behind start
t = 1;
}
if ( h < 1 )
{ // Prevents hare from slipping behind start
h = 1;
}
if ( t > 50 )
{ // Prevents tortoise from going passed finish line
t = 50;
}
if ( h > 50 )
{ // Prevents hare from going passed finish line
h = 50;
}
for ( int count = 1; count <= 50; count++)
{
System.out.print( "_" );
if ( count == h )
{
System.out.print( "H" );
}
if ( count == t )
{
System.out.print( "T" );
}
}
if (h < 50 && t == 50)
{ //Output if tortoise wins
System.out.print( "TORTOISE WINS!!" );
}
if ( t < 50 && h == 50)
{ // Output if hare wins
System.out.print( "HARE WINS!!" );
}
if ( h == 50 && t == 50)
{
System.out.print( "IT'S A TIE!!" );
}
}
}
/**
* This method will calculate the random integer that will dictate the tortoise's movements on the board,
* use that random integer to determine the tortoise's movements (tMove), and add that to the counter keeping track
* of the tortoise's position
* #param t is an int variable that is keeping track of the tortoises position on the board
* #return the tortoise's current position on the board after that turn
* Pre-Conditions: n is an int between 1 and 10, t is a positive int greater than 0 and less than 50
*/
public static int tortoiseMove (int t)
{
int n;
int tMove = 0;
n = (int) ( 10 * Math.random() ) + 1; // Generates random number between 1 and 10
if ( n > 10 )
{ // ensures n doesn't go higher than 10
n = 10;
}
// Series of if/else statements to control tMove
if ( n >= 1 && n <= 5)
{ // Fast plod if n is between 1 and 5
tMove = 3;
}
else
{
if ( n >= 6 && n <= 8)
{ // Slow Plod if n is between 6 and 8
tMove = 1;
}
else
{
if ( n == 9 || n == 10 )
{ // Slip if n is 9 or 10
tMove = -6;
}
}
}
// Add determined movement to tortoise counter and return that value
t += tMove;
return t;
}
/**
* This method will calculate the random integer that will dictate the hare's movements on the board,
* use that random integer to determine the hare's movements (hMove), and add that to the counter keeping track
* of the hare's position on the board
* #param h is an int variable keeping track of the hare's current position on the board
* #return the hare's position on the board after current turn
* Pre-Condition: n is an int between 1 and 10, h is a positive int greater than 0 and less than 50
*/
public static int hareMove (int h)
{
int n;
int hMove = 0;
n = (int) ( 10 * Math.random() ) + 1; // Generates random number between 1 and 10
if ( n > 10 )
{ // ensures n doesn't go higher than 10
n = 10;
}
//Series of if/else statements to control hMove
if ( n == 1 || n == 2 )
{ // Big hop if n is 1 or 2
hMove = 9;
}
else
{
if ( n >= 3 && n <= 5)
{ // Small hop is n is between 3 and 5
hMove = 1;
}
else
{
if ( n == 6 )
{ // Big slip is n is 6
hMove = -12;
}
else
{
if ( n == 7 || n == 8 )
{ // Small slip if n is 7 or 8
hMove = -2;
}
else
{
if ( n == 9 || n == 10 )
{ // Hare falls asleep if n is 9 or 10
hMove = 0;
}
}
}
}
}
// Add determined movement to hare counter and return value of h
h += hMove;
return h;
}
}
You never reassign h and t after moving
h = hareMove( h );
t = tortoiseMove( t );
Primitives are passed by value, so whatever change you made to h and t in the move method are not reflected in the original values.

Java finding full routes in NxN grid [duplicate]

This question already has answers here:
How do I do a deep copy of a 2d array in Java?
(7 answers)
Closed 8 years ago.
So I am trying to make an algorithm for finding full paths in NxN grid. For example in 1x1 grid there is 1 possible path, in 2x2 grid there is 1, in 3x3 there is 2 and in 4x4 there is 8. The idea is to find scenarios where we can fill every spot of the grid by moving.
I have made a recursive function for the job and here is the code:
public static int getRoutesHelp(int[][] table, int x, int y)
{
if(x > table.length-1 || x < 0 || y < 0 || y > table.length-1)
return 0;
if(table[x][y] == 1)
return 0;
table[x][y] = 1;
if(isDeadEnd(table, x, y))
{
if(isTableFull(table))
return 1;
}
else
{
int a = getRoutesHelp(table, x-1, y);
int d = getRoutesHelp(table, x, y+1);
int b = getRoutesHelp(table, x+1, y);
int c = getRoutesHelp(table, x, y-1);
return a+b+c+d;
}
return 0;
}
public static int getRoutes(int size)
{
int[][] table = new int[size][size];
// init table
for(int i = 0; i < size; i++)
{
for(int a = 0; a < size; a++)
{
table[i][a] = 0;
}
}
return getRoutesHelp(table, 0 ,0);
}
So basically I start from 0.0 and start moving to all possible directions and by repeating this I get the amount of successful routes. The problem is that after the assignment of int d the original table is somehow filled with 1 but it should be empty as far as I understand because java passes a copy of the table right? I've been fighting with this for like 4 hours and can't really find the problem so any help is appreciated. Empty slots in table are marked with 0 and filled slots with 1.
EDIT: I managed to fix the issue I had with the copying and now my other problem is that with 5x5 grid my algorithm returns 52 routes and it should be 86. So it works with 4x4 grid okay, but once I move further it breaks.
Added the isDeadEnd function here
public static boolean isDeadEnd(int[][] table, int x, int y)
{
int toCheck[] = new int[4];
toCheck[0] = x-1; // left
toCheck[1] = y-1; // top
toCheck[2] = x+1; // right
toCheck[3] = y+1; // bottom
int valuesOfDirections[] = new int[4]; // left, top, right, bottom
for(int i = 0; i < 4; i++)
{
int tarkastettava = toCheck[i];
if(tarkastettava > table.length-1 || tarkastettava < 0)
{
valuesOfDirections[i] = 1;
}
else
{
if(i == 0 || i == 2)
{
valuesOfDirections[i] = table[tarkastettava][y];
}
else
{
valuesOfDirections[i] = table[x][tarkastettava];
}
}
}
for(int i = 0; i < 4; i++)
{
if(valuesOfDirections[i] == 0)
{
return false;
}
}
return true;
}
Come to think of it, you probably can do a simple backtrack here:
table[x][y] = 1;
if(isDeadEnd(table, x, y)) {
if(isTableFull(table))
return 1;
}
table[x][y] = 0;
}
And later:
int res = a + b + c + d;
if (res == 0) {
// backtrack here too
table[x][y] = 0;
}
return res;

Cheking the surrounding indexes around an index in 2d matrix

I'm working on the Conway's game of life program and I'm at the point where the dead/live cell checks it's surrounding neighbors and counts the amount of live neighbors surrounding it. Right now, I'm working on having [0][0] checked. The problem I'm having is that [0][0] is being checked along with the surrounding indexes. I thought if I were to put " if (k!=o && l!=p)", it would exclude [0][0], but it doesn't.
public class Life {
public static void main(String[] args)
{
int N = 5;
boolean[][] b = new boolean[N][N];
double cellmaker = Math.random();
int i = 0;
int j = 0;
int o=0;
int p=0;
int livecnt = 0; //keeps track of the alive cells surrounding cell
System.out.println("First Generation:");
// Makes the first batch of cells
for ( i = 0; i < N ; i++)
{
for ( j = 0; j< N; j++)
{
cellmaker = Math.random();
if (cellmaker > 0.5) // * = alive; - = dead
{
b[i][j]=true;
System.out.print( "* ");
}
if (cellmaker < 0.5)
{ b[i][j] = false;
System.out.print("- ");
}
}
System.out.println();
}
// Checks for the amount of "*" surrounding (o,p)
for (int k=(o-1); k <= o+1; k++ )
{
for (int l =(p-1); l <=p+1; l++)
{
if ( k >= 0 && k < N && l >= 0 && l < N) //for the border indexes.
{
//if (k!=o && l!=p)
{
if (b[k][l] == true)
{
livecnt++;
}
}
}
}
}
System.out.println(livecnt++);
}
}
You want to check the surrounding of (o,p), try something like this:
if (!(k== o && l==p))
instead of:
if (k!=o && l!=p)
because with the above condition you are not checking the coordinates (k,p-1), (k,p+1), (k-1,p) and (k+1,p)
Your code is nearly correct. You just need to change
if (k!=o && l!=p)
into
if (k!=o || l!=p)
You only want to count a field if the coordinates (k,l) are not equal to (o,p)
In other words: !(k==o && l==p)
Remember (k!=o || l!=p) is equal to !(k==o && l==p)
according to De Morgan's laws.

Categories