Reputation: 626
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++);
}
}
Upvotes: 1
Views: 298
Reputation: 8139
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.
Upvotes: 2
Reputation: 51443
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)
Upvotes: 2