Euler28.java 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. public class Euler28 {
  2. private static void printArray(int[][] spiral, int N) {
  3. for (int i = 0; i < N; i++) {
  4. for (int j = 0; j < N; j++) {
  5. System.out.print(spiral[i][j] + " ");
  6. }
  7. System.out.println("");
  8. }
  9. }
  10. private static int getSum(int[][] array, int N) {
  11. int sum = 0;
  12. // Summe berechnen
  13. for (int i = 0; i < N; i++) {
  14. sum += array[i][i]; // Diagonale 1, links oben nach rechts unten
  15. sum += array[N - 1 - i][i]; // Diagonale 2, rechts oben nach links
  16. // unten
  17. }
  18. sum -= 1; // die 1 liegt auf beiden Diagonalen
  19. return sum;
  20. }
  21. enum Direction {
  22. RECHTS, UNTEN, OBEN, LINKS
  23. }
  24. public static void main(String[] args) {
  25. final int N = 5;
  26. // initialise variables
  27. int[][] spiral = new int[N][N];
  28. Direction direction = Direction.RECHTS;
  29. int posX = N / 2;
  30. int posY = N / 2;
  31. int steps = 1;
  32. int number = 1;
  33. // fill array with spiral values
  34. while (number <= N * N) {
  35. for (int j = 0; j < steps; j++) {
  36. spiral[posX][posY] = number;
  37. switch (direction) {
  38. case RECHTS:
  39. posX++;
  40. break;
  41. case UNTEN:
  42. posY++;
  43. break;
  44. case LINKS:
  45. posX--;
  46. break;
  47. case OBEN:
  48. posY--;
  49. break;
  50. }
  51. number++;
  52. if (number > N * N) {
  53. break;
  54. }
  55. }
  56. switch (direction) {
  57. case RECHTS:
  58. direction = Direction.UNTEN;
  59. break;
  60. case UNTEN:
  61. direction = Direction.LINKS;
  62. steps++;
  63. break;
  64. case LINKS:
  65. direction = Direction.OBEN;
  66. break;
  67. case OBEN:
  68. direction = Direction.RECHTS;
  69. steps++;
  70. break;
  71. }
  72. }
  73. printArray(spiral, N);
  74. System.out.println("Diagonal-Summe: " + getSum(spiral, N));
  75. }
  76. }