-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay3_Part2.java
More file actions
99 lines (86 loc) · 2.23 KB
/
Copy pathDay3_Part2.java
File metadata and controls
99 lines (86 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
public class Day3_Part2 {
private static final int INITIAL_SIZE = 5;
public static void main(String[] args) {
int numberToCheck = 312051;
int size = INITIAL_SIZE;
int currentSum = 0;
int[][] map = new int[size][size];
map[size/2][size/2] = 1;
int currentX = 2;
int currentY = 3;
Direction direction = Direction.RIGHT;
do
{
if (currentX == (size - 2) && currentY == (size - 1))
{
currentX++;
currentY++;
size += 2;
map = populateDataToNewMap(size, map);
}
currentSum = getSumOfCurrentCell(map, currentX, currentY);
map[currentX][currentY] = currentSum;
switch (direction) {
case LEFT:
if (map[currentX + 1][currentY] == 0) {
direction = Direction.DOWN;
currentX = currentX + 1;
} else {
direction = Direction.LEFT;
currentY = currentY - 1;
}
break;
case RIGHT:
if (map[currentX - 1][currentY] == 0) {
direction = Direction.UP;
currentX = currentX - 1;
} else {
direction = Direction.RIGHT;
currentY = currentY + 1;
}
break;
case UP:
if (map[currentX][currentY - 1] == 0) {
direction = Direction.LEFT;
currentY = currentY - 1;
} else {
direction = Direction.UP;
currentX = currentX - 1;
}
break;
case DOWN:
if (map[currentX][currentY + 1] == 0) {
direction = Direction.RIGHT;
currentY = currentY + 1;
} else {
direction = Direction.DOWN;
currentX = currentX + 1;
}
break;
default:
break;
}
}
while (currentSum < numberToCheck);
System.out.println(currentSum);
}
private static int[][] populateDataToNewMap(int size, int[][] map) {
int[][] newMap = new int[size][size];
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map.length; j++)
{
newMap[i + 1][j + 1] = map[i][j];
}
}
return newMap;
}
private static int getSumOfCurrentCell(int[][] map, int currentY, int currentX)
{
return map[currentY + 1][currentX] + map[currentY - 1][currentX] + map[currentY][currentX + 1]
+ map[currentY][currentX - 1] + map[currentY + 1][currentX + 1] + map[currentY + 1][currentX - 1]
+ map[currentY - 1][currentX + 1] + map[currentY - 1][currentX - 1];
}
enum Direction {
LEFT, RIGHT, UP, DOWN;
}
}