Posted By

donfips on 12/17/09


Tagged

GOL hsrm


Versions (?)

Game of Life


 / Published in: Java
 

  1. public class SpielDesLebens {
  2. public static void main(String[] args){
  3. int msize = field();
  4. int[][]setrix;
  5. int[][] matrix = new int [msize][msize];
  6. for(int i = 0; i < msize; i++ ){
  7. System.out.print("Eingabe der " + (i+1) + ".Zeile: ");
  8. String s = In.readString();
  9. for(int j = 0; j < msize; j++ ){
  10. matrix[i][j] = Integer.parseInt(s.substring(j , j+1));
  11. }
  12. }
  13. setrix = compare(matrix);
  14. output(matrix);
  15. output(setrix);
  16. }
  17. public static int[][] compare(int[][] matrix){
  18. int z;
  19. int[][] setrix = new int [matrix.length][matrix.length];
  20. for(int y = 0; y < matrix.length; y++){
  21. for(int x = 0; x < matrix.length; x++){
  22. z = 0;
  23. for(int shifty = -1; shifty <= 1; shifty++){
  24. for(int shiftx = -1; shiftx <= 1; shiftx++){
  25. int nachbarx = x+shiftx;
  26. int nachbary = y+shifty;
  27. if (nachbarx < 0) nachbarx = (nachbarx + matrix.length);
  28. if (nachbary < 0) nachbary = (nachbary + matrix.length);
  29. if (nachbarx >= matrix.length) nachbarx = (nachbarx - matrix.length);
  30. if (nachbary >= matrix.length) nachbary = (nachbary - matrix.length);
  31. if (nachbarx == x && nachbary == y) continue;
  32. if (matrix[nachbary][nachbarx] > 0) z++;
  33. }
  34. }
  35. setrix [y][x] = 0;
  36. if (matrix [y][x] == 1 && (z == 2 || z == 3)) setrix [y][x] = 1;
  37. if (matrix [y][x] == 0 && z == 3) setrix [y][x] = 1;
  38. }
  39. }
  40. return setrix;
  41. }
  42. public static void output(int[][] matrix){
  43. for(int i = 0; i < matrix.length; i++){
  44. for(int j = 0; j < matrix.length; j++){
  45. System.out.print(matrix[i][j]);
  46. }
  47. System.out.println();
  48. }
  49. System.out.println("~~~~~~~");
  50. }
  51. public static int field(){
  52. int z;
  53. System.out.println("Bitte geben Sie die Dimension der Matrix an (n*n): ");
  54. z = In.readInt();
  55. System.out.println("Die Matrix hat die Groesse " + z + "*" + z + " Felder.");
  56. return z;
  57. }
  58. }

Report this snippet  

You need to login to post a comment.