Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import chn.util.*;
- import apcslib.*;
- import java.util.*;
- public class Life {
- public void printTable (int[][] pTable){
- int totalAlive = 0;
- System.out.print(" ");
- for (int i = 1; i <= 2; i++){
- for (int k = 1; k <= 9; k++){
- System.out.print(k);
- }
- System.out.print("0");
- }
- System.out.println();
- for (int row = 1; row < pTable.length - 1; row++){
- System.out.print(Format.right(row, 2));
- for (int col = 1; col < (pTable[row].length); col++){
- if(pTable[row][col] == 1){
- System.out.print("*");
- totalAlive += 1;
- }
- else System.out.print(" ");
- }
- System.out.println();
- }
- System.out.println("Number in Row 10 ---> " +checkRow(pTable, 10));
- System.out.println("Number in Column 10 ---> " + checkCol(pTable, 10));
- System.out.println("Number of living organisms ---> " + totalAlive);
- }
- public static int[][] zeroGeneration(FileInput inFile, int[][] currentTable){
- int number = inFile.readInt();
- int row, col;
- while(inFile.hasMoreTokens()){
- row = inFile.readInt();
- col = inFile.readInt();
- currentTable[row][col] = 1;
- }
- return currentTable;
- }
- public static int checkNeighbors(int[][] currentTable, int r, int c){
- int neighbors = 0;
- for (int row = -1; row <= 1; row++){
- for (int col = -1; col <= 1; col++){
- if (currentTable[r + row][c + col] == 1 && (row != 0 || col != 0))
- neighbors++;
- }
- }
- return neighbors;
- }
- public static int[][] nextGeneration(int[][]currentTable){
- int[][] scratchTable = new int[22][22];
- for(int row = 1; row <= 20; row++){
- for (int col = 1; col <= 20; col++){
- if (currentTable[row][col] == 1){
- if (checkNeighbors(currentTable, row, col) < 2 || checkNeighbors(currentTable, row, col) > 3){
- scratchTable[row][col] = 0;
- }
- else scratchTable[row][col] = 1;
- }
- else if(checkNeighbors(currentTable, row, col) == 3){
- scratchTable[row][col] = 1;
- }
- }
- }
- return scratchTable;
- }
- public static int checkRow(int[][] currentTable, int cell){
- int rowAlive = 0;
- for (int col = 0; col < currentTable[cell].length; col++){
- if (currentTable[cell][col] == 1){
- rowAlive += 1;
- }
- }
- return rowAlive;
- }
- public static int checkCol(int[][] currentTable, int cell){
- int colAlive = 0;
- for (int row = 0; row < currentTable.length; row++){
- if (currentTable[row][cell] == 1){
- colAlive += 1;
- }
- }
- return colAlive;
- }
- public static void main(String[] args) {
- FileInput inFile = new FileInput("life100.txt");
- Life test = new Life();
- int[][] firstTable = new int[22][22];
- firstTable = zeroGeneration(inFile, firstTable);
- int[][] nextTable = new int[22][22];
- nextTable = nextGeneration(firstTable);
- for(int i = 1; i < 5; i++){
- nextTable = nextGeneration(nextTable);
- }
- test.printTable(nextTable);
- }
- }
- `
Advertisement
Add Comment
Please, Sign In to add comment