Examples of smaller Java programs that do various interesting things.

Life.java 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import java.util.Scanner;
  2. public class Life {
  3. public static void show(boolean[][] grid){
  4. String s = "";
  5. for(boolean[] row : grid){
  6. for(boolean val : row)
  7. if(val)
  8. s += "*";
  9. else
  10. s += ".";
  11. s += "\n";
  12. }
  13. System.out.println(s);
  14. }
  15. public static boolean[][] gen(){
  16. boolean[][] grid = new boolean[10][10];
  17. for(int r = 0; r < 10; r++)
  18. for(int c = 0; c < 10; c++)
  19. if( Math.random() > 0.7 )
  20. grid[r][c] = true;
  21. return grid;
  22. }
  23. public static void main(String[] args){
  24. boolean[][] world = gen();
  25. show(world);
  26. System.out.println();
  27. world = nextGen(world);
  28. show(world);
  29. Scanner s = new Scanner(System.in);
  30. while(s.nextLine().length() == 0){
  31. System.out.println();
  32. world = nextGen(world);
  33. show(world);
  34. }
  35. }
  36. public static boolean[][] nextGen(boolean[][] world){
  37. boolean[][] newWorld
  38. = new boolean[world.length][world[0].length];
  39. int num;
  40. for(int r = 0; r < world.length; r++){
  41. for(int c = 0; c < world[0].length; c++){
  42. num = numNeighbors(world, r, c);
  43. if( occupiedNext(num, world[r][c]) )
  44. newWorld[r][c] = true;
  45. }
  46. }
  47. return newWorld;
  48. }
  49. public static boolean occupiedNext(int numNeighbors, boolean occupied){
  50. if( occupied && (numNeighbors == 2 || numNeighbors == 3))
  51. return true;
  52. else if (!occupied && numNeighbors == 3)
  53. return true;
  54. else
  55. return false;
  56. }
  57. private static int numNeighbors(boolean[][] world, int row, int col) {
  58. int num = world[row][col] ? -1 : 0;
  59. for(int r = row - 1; r <= row + 1; r++)
  60. for(int c = col - 1; c <= col + 1; c++)
  61. if( inbounds(world, r, c) && world[r][c] )
  62. num++;
  63. return num;
  64. }
  65. private static boolean inbounds(boolean[][] world, int r, int c) {
  66. return r >= 0 && r < world.length && c >= 0 &&
  67. c < world[0].length;
  68. }
  69. }