Well once again I have some trouble getting my lab to work. I am currently having trouble on an algorithm that is supposed to count the neighbors next to a cell in a Two-dimensional array which is supposed to resemble with the algorithm of Conway's Game of Life. For some reason becuase reason it doesnt seem to be working. I have everything else done and would gladly appriciate some help.

import apcslib.*; import chn.util.*;

public class Life
{
	boolean alive = false;
	boolean[][] board = new boolean[21][21];
	boolean[][] nextBoard = new boolean[21][21];
		
	FileInput inFile;
	FileOutput outFile;
	
	public Life(String input, String output)
	{
		inFile = new FileInput(input);
  		outFile = new FileOutput(output);	
	}
	
	public void cellConstruct()
	{
		int pairNumbers = inFile.readInt();
		int count = 0;
		int x, y;
		int width = 20;
		
		while (inFile.hasMoreTokens())
  		{
  			x = inFile.readInt();
  			y = inFile.readInt();
  			count++;

        	board[x][y] = true;
        }
        
	}
	
	public void setAlive(int x, int y, boolean alive)
	{
    	board[x][y] = true;
	}
	
	public boolean CellIsAlive(int i, int j)
	{
		return board[i][j];
	}
	
	public int countLiveNeighbors (int i, int j)
    {
    	int limit = 21 - 1;
    	int count = 0;
    	for (int ii = i - 1; ii <= i + 1; ii++)
    	{
      		for (int jj = j - 1; jj <= j + 1; jj++)
      			{
					if (ii == i && jj == j) continue;
						if (ii < 0 || ii > limit) continue;
							if (jj < 0 || jj > limit) continue;
								if (CellIsAlive (ii, jj) == true) count++;
      			}
    	}
    	return count;
    }
    
  public void execute(int numberSteps)
  {
  	int numberOfSteps = numberSteps;
  	int numberOfNeighbors;
  	
    	for (int step = 0; step < numberOfSteps; step++)
    	{
    		for (int row = 0; row < nextBoard.length; row++)
    		{
      			for (int col = 0; col < nextBoard[row].length; col++)
      			{
      				nextBoard[row][col] = board[row][col];
      			}
      		}
      		
      		// Set up an empty board and fill it with value for next step
      		for (int i = 0; i < 21; i++)
        	{	
        		for (int j = 0; j < 21; j++)
        		{
          			numberOfNeighbors = countLiveNeighbors(i, j);
          			if (CellIsAlive(i, j))
	  				{
	    				if (numberOfNeighbors == 2 || numberOfNeighbors == 3)
	      					nextBoard[i][j] = true;
	  				}
	  				else // cell is dead
	    				if (numberOfNeighbors != 3 || numberOfNeighbors != 2)
	     					nextBoard[i][j] = false;

        		}
			}
			
      		for (int row = 0; row < board.length; row++)
    		{
      			for (int col = 0; col < board[row].length; col++)
      			{
      				board[row][col] = nextBoard[row][col];
      			}
      		}
      		
      		print();
      		outFile.close();
    	}
    }
  	
  	public void print ()
  	{
  		outFile.println(Format.left("      1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20",4));
  		outFile.println("");
  		
   	 	for (int row = 1; row < board.length; row++)
    	{
    		outFile.print(Format.left(row,4));
    		
      		for (int col = 1; col < board[row].length; col++)
      		{
      			if (board[row][col] == true)
      			{
      				outFile.print(Format.right("*",3));
      			}
      			else
				{
        			outFile.print(Format.right(" ",3));
        		}
        	}
      	outFile.println();
    	}
  	}
}

class LifeOutput
{
	public static void main (String args[])
  	{
  		ConsoleIO input = new ConsoleIO();
  		int numberOfSteps;
  		String fileInput;
  		
  		System.out.println("Welcome to Life.");
  		System.out.println("");
  		System.out.println("Please enter name of the file to be read: ");
  		fileInput = input.readLine();
  		System.out.println("Please enter the # of generations to elaspe: ");
  		numberOfSteps = input.readInt();
  		System.out.println("");
  		System.out.println("Executing....");
  		System.out.println("");
  		
    	Life lifeS = new Life(fileInput,"fileout.txt");
    	
    	lifeS.cellConstruct();
    	lifeS.execute(numberOfSteps);
  	}
}

The lab to this program can be found 'Here'

Once again thanks in advance,

Lord Felix

PS: I figured out the error with my previous post so thanks anyways.

Recommended Answers

All 7 Replies

For some reason becuase reason it doesnt seem to be working

huh? What are you trying to say here?

What isn't working and why isn't it working.
What is it doing and what is it supposed to be doing?

Sorry for making it unclear. I have to write a program that simulates the game of Life using Two-Dimensional arrays. The size of the grid will be a square 20 x 20 (Which is size of the Two-Dimensional Array). My program is supposed to read the locations of the cells that are in a text file and then store them into the Two-Dimension array. Once stored I have to use an algorithm to read the Two-Dimensional array and search for cells that have neighboring cells and apply Conway's Game of Life rules to them for a set amount of generations (Loops).

His rules of the Game are here if you arn't familiar with them:

A "neighbor" of a cell is defined as any cell touching that cell, for example the eight blue cells in the diagram are the neighbors of the cell in the middle.

Every empty cell with three living neighbors will come to life in the next generation (a "birth").

Any cell with one or zero neighbors will die of loneliness, while any cell with four or more neighbors will die from overcrowding (a "death").

Any cell with two or three neighbors will live into the next generation (no change).

All births and deaths occur simultaneously.

Well the problem I have my the code is that my method to count the number of cells that surround a cell is either wrong or not functional. I need someone to go over my code to see if Im using my methods write and help me fix my "public int countLiveNeighbors (int i, int j)" method.

Sorry for confusion,

Lord Felix

public int countLiveNeighbors (int i, int j)
    {
    	int limit = 21 - 1;
    	int count = 0;
    	for (int ii = i - 1; ii <= i + 1; ii++)
    	{
      		for (int jj = j - 1; jj <= j + 1; jj++)
      		{
			if (ii == i && jj == j) continue;
			if (ii < 0 || ii > limit) continue;
			if (jj < 0 || jj > limit) continue;
			if (CellIsAlive (ii, jj) == true) count++;
      		}
    	}
    	return count;
    }

looks correct.
Your actual problem is over here:

for (int i = 0; i < 21; i++)
      {	
        	for (int j = 0; j < 21; j++)
        	{
          		numberOfNeighbors = countLiveNeighbors(i, j);
          		if (CellIsAlive(i, j))
	 	{
	    		if (numberOfNeighbors == 2 || numberOfNeighbors == 3)
	      			nextBoard[i][j] = true;
	  	}
	  	else // cell is dead
	    		if (numberOfNeighbors != 3 || numberOfNeighbors != 2)
	     			nextBoard[i][j] = false;

        	}
}

This doesn't take into account that cells can come alive if they're dead.
While you ARE taking celldeath into account on life cells, you're not taking cellbirth into account therefore your simulation will either die quickly or reach a single stable and unchanging state.

change

else // cell is dead
	    		if (numberOfNeighbors != 3 || numberOfNeighbors != 2)
	     			nextBoard[i][j] = false;

to take that condition into account.
Remember that the default values for an array of booleans are all false, so setting them to false is not needed.
But explicitly setting them to true when they should be IS needed, and you're not doing that.

Also I don't think you need to prefill the board with the old position.
Just initialising the array and setting those positions to true that hold life cells in the new position based on calculating the count and status from the old position should be enough.
This will remove an entire loop from your simulation, possibly speeding it up quite a bit.

a P.S.: be careful with indentation and braces.
Having it poorly done (like in your code, with braces not lined up and indenting with both tabs and spaces interspersed) can make code a lot harder to read.
I had to reformat your code to be able to quickly see how it is structured.

Thanks jwenting, that helped alot. As for the messy coding, I initially had to copy and paste the code from the computer in my school so it messed up the format of the coding. Sorry for that inconveinance. Ill go revise that part of the code. :cheesy:

Lord Felix

Alright, I revised that part of the code:

for (int i = 0; i < 21; i++)
      		{	
        		for (int j = 0; j < 21; j++)
        		{
          			numberOfNeighbors = countLiveNeighbors(i, j);
          			if (CellIsAlive(i, j) == true)
				 	{
			    		if (numberOfNeighbors <= 1 || numberOfNeighbors > 3)
			      			nextBoard[i][j] = false;
	  				}
	  				
	 				if (CellIsAlive(i, j) == false)
	 				{
	 					if (numberOfNeighbors == 3)
	 						nextBoard[i][j] = true;
	 				}

				}
			}

The program is stuck on the first generation however.

Aliright, I figured out that I closed the file too soon and thats what cuased the program to appear to be stuck at the first generation. The only problem I have right now is that cells that do not have neighbors are not dying in the next generation. I did some debugging and it seems that the program is reading in the cells that have no neighbors to have 2 neighbors. With this in mind, I think am currently looking over the program to see why this is so. Help would gladly be accepted as I am wanting to get it done.

Thanks,

Lord Felix

PS: I would edit my posts if there was a funtion to edit even after one day, sorry for the triple post.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.