Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

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