This repository was archived by the owner on Dec 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 501
Expand file tree
/
Copy pathSpiral.java
More file actions
85 lines (76 loc) · 2.59 KB
/
Copy pathSpiral.java
File metadata and controls
85 lines (76 loc) · 2.59 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
import java.util.Arrays;
public class Spiral {
private enum Direction {
UP, DOWN, LEFT, RIGHT
}
private boolean isCoordinateValid(int height, int width, int row, int column) {
return (row > 0 && row <= height) && (column > 0 && column <= width);
}
private int getNumberAtCoordinate(int width, int row, int column) {
return column + (row - 1) * width;
}
private int[] getNextCoordinate(int row, int column, Direction currentDirection) {
int[] nextCoordinate = new int[2];
nextCoordinate[0] = row;
nextCoordinate[1] = column;
switch (currentDirection) {
case UP:
nextCoordinate[0] -= 1;
break;
case LEFT:
nextCoordinate[1] -= 1;
break;
case DOWN:
nextCoordinate[0] += 1;
break;
case RIGHT:
nextCoordinate[1] += 1;
break;
}
return nextCoordinate;
}
private Direction getNextDirection(Direction currentDirection) {
switch (currentDirection) {
case UP:
return Direction.LEFT;
case LEFT:
return Direction.DOWN;
case DOWN:
return Direction.RIGHT;
case RIGHT:
return Direction.UP;
default:
return currentDirection;
}
}
public int[] spiral(int height, int width, int row, int column) {
int numberOfElements = height * width;
int[] output = new int[numberOfElements];
int outputIndex = 0;
Direction currentDirection = Direction.UP;
int stepsTaken = 0;
int stepsNeeded = 1;
while (outputIndex < numberOfElements) {
if (isCoordinateValid(height, width, row, column)) {
output[outputIndex++] = getNumberAtCoordinate(width, row, column);
}
int[] nextCoordinate = getNextCoordinate(row, column, currentDirection);
row = nextCoordinate[0];
column = nextCoordinate[1];
++stepsTaken;
if (stepsTaken == stepsNeeded) {
if (currentDirection == Direction.LEFT || currentDirection == Direction.RIGHT) {
++stepsNeeded;
}
stepsTaken = 0;
currentDirection = getNextDirection(currentDirection);
}
}
return output;
}
public static void main(String[] args) {
Spiral s = new Spiral();
System.out.println(Arrays.toString(s.spiral(5, 5, 3, 3)));
System.out.println(Arrays.toString(s.spiral(2, 4, 1, 2)));
}
}