Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // I have everything working except for the dead cell rule
- import java.util.Arrays;
- import java.util.Random;
- public class GOL {
- public static void main(String[] args)
- {
- Cell newcell = new Cell(0);
- int board[][] = new int[5][5];
- Random rand = new Random();
- //https://stackoverflow.com/questions/43314281/random-matrix-fill-between-1-and-0-in-java
- for (int i = 0; i < 5; i++)
- {
- for (int j = 0; j < 5; j++)
- {
- // you could maybe do a random initialization of board before you start checking for the cells
- // in that way it will be more obvious where the problem is defined and when you start to find the solution
- board[i][j] = rand.nextInt(2);
- try{
- // don't use this object(newcell) just in order to be able to call method of it's class,
- // it would be better to make that method static so Cell.getNumberofNeighbors(),
- // look on when to use static methods,
- // or if you make class Board that consists of Cell's you could write it like this
- // board.getNumberOfNeighborsForCurrentCell(cell. or i,j whatever),
- // if you do it like this there is no need to pass the whole matrix everytime,
- // but even then there is space for improvement in class Board make method isDying(cell),
- // add your methods for every rule, that will improve readability, it will be more like a story...
- if (newcell.getNumberofNeighbors(i, j, board) < 2)
- {
- board[i][j] = 0;
- }
- if (newcell.getNumberofNeighbors(i, j, board) > 3)
- {
- board[i][j] = 0;
- }
- }
- catch (Exception e) {
- //https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array
- System.out.println(Arrays.deepToString(board).replace("], " + "[", "\n"));
- }
- }
- }
- }
- }
- import java.util.Arrays;
- import java.util.Random;
- public class Cell {
- int numberofneighbors;
- public Cell(int numberofneighbors)
- {
- this.numberofneighbors = numberofneighbors;
- }
- // optimize your parameters, naming is not good, third arg. is really not position
- // it is the whole board(your matrix), so this is rather confusing
- public int getNumberofNeighbors(int x, int y, int[][] position) throws Exception
- {
- if ((x < 0) || (y < 0) || (x > 5) || (y > 5)) { throw new Exception(""); }
- else
- {
- if (position[x][y] == 1)
- {
- if (position[x][y + 1] == 1) { numberofneighbors += 1; }
- if (position[x + 1][y] == 1) { numberofneighbors += 1; }
- if (position[x + 1][y + 1] == 1) { numberofneighbors += 1; }
- if (position[x - 1][y] == 1) { numberofneighbors += 1; }
- if (position[x][y - 1] == 1) { numberofneighbors += 1; }
- if (position[x + 1][y - 1] == 1) { numberofneighbors += 1; }
- if (position[x - 1][y + 1] == 1) { numberofneighbors += 1; }
- }
- }
- return numberofneighbors;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement