Advertisement
Guest User

Untitled

a guest
May 2nd, 2016
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.91 KB | None | 0 0
  1. public class Main {
  2.  
  3. // booleans in place of string, resolve boolean in print method
  4. // global variables are unnecessary
  5.  
  6. public static final int size = 10;
  7.  
  8. public static void main(String [] args) throws Exception {
  9. boolean[][] board = createBoard();
  10.  
  11. while (true) {
  12. printBoard(board);
  13. board = updateBoard(board);
  14. Thread.sleep(500);
  15. System.out.println();
  16. }
  17. }
  18.  
  19. public static boolean[][] createBoard() {
  20. boolean[][] board = new boolean[size][size];
  21. for (int x = 0; x < size; x++) {
  22. for (int y = 0; y < size; y++) {
  23. if (x == 0 && y == 2) {
  24. board[x][y] = true;
  25. }
  26. if (x == 1 && y == 3) {
  27. board[x][y] = true;
  28. }
  29. if (x == 2 && y == 1) {
  30. board[x][y] = true;
  31. }
  32. if (x == 2 && y == 2) {
  33. board[x][y] = true;
  34. }
  35. if (x == 2 && y == 3) {
  36. board[x][y] = true;
  37. }
  38. }
  39. }
  40. return board;
  41. }
  42.  
  43. public static void printBoard(boolean[][] board) {
  44. for (int x = 0; x < size; x++) {
  45. for (int y = 0; y < size; y++) {
  46. if (board[x][y]) {
  47. System.out.print("[X]");
  48. } else {
  49. System.out.print("[ ]");
  50. }
  51. }
  52. System.out.println();
  53. }
  54. }
  55.  
  56. public static boolean[][] updateBoard(boolean[][] board) {
  57. boolean[][] newBoard = new boolean[size][size];
  58. for (int x = 0; x < size; x++) {
  59. for (int y = 0; y < size; y++) {
  60. int neighbors = getNeighbors(board, x, y);
  61.  
  62. boolean cell = board[x][y];
  63.  
  64. if (cell && neighbors < 2) {
  65. newBoard[x][y] = false;
  66. } else if (cell && (neighbors == 2 || neighbors ==3)) {
  67. newBoard[x][y] = true;
  68. } else if (cell && neighbors > 3) {
  69. newBoard[x][y] = false;
  70. } else if (!cell && neighbors == 3) {
  71. newBoard[x][y] = true;
  72. }
  73. }
  74. }
  75. return newBoard;
  76. }
  77.  
  78. public static int getNeighbors(boolean[][] board, int x, int y) {
  79. int count = 0;
  80. for (int i = -1; i <2; i++) {
  81. for (int j = -1; j <2; j++) {
  82. if (x == x - i && y == y - j) {
  83. continue;
  84. }
  85. if (x - i < 0 || y - j < 0 || x - i > size - 1 || y - j > size - 1) {
  86. continue;
  87. }
  88. if (board[x - i][y - j]) {
  89. count++;
  90. }
  91. }
  92. }
  93. return count;
  94. }
  95.  
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement