-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpiralPrint.java
72 lines (57 loc) · 2.25 KB
/
SpiralPrint.java
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
import java.util.Arrays;
class SpiralPrint {
public static void main(String[] args) {
int[][] oddInput = new int[][]{{ 1, 2, 3, 4, 5},
{16, 17, 18, 19, 6},
{15, 24, 25, 20, 7},
{14, 23, 22, 21, 8},
{13, 12, 11, 10, 9}};
int[][] evenInput = new int[][]{{ 1, 2, 3, 4},
{12, 13, 14, 5},
{11, 16, 15, 6},
{10, 9, 8, 7}};
printSpiral(oddInput);
printSpiral(evenInput);
}
private static void printSpiral(int[][] input) {
if(input.length != input[0].length) {
return;
}
int[] printArray = new int[input.length * input.length];
int printCounter = 0;
int size = input[0].length;
int numIterations = size / 2;
int bias = 0;
int loop1Row = 0;
int loop2Column = size - 1;
int loop3Row = size - 1;
int loop4Column = 0;
for(int iteration = 0; iteration < numIterations; iteration++) {
//Horizontal Left to Right
for(int i = 0 + bias; i < size - 1 - bias; i++) {
printArray[printCounter++] = input[loop1Row][i];
}
// Vertical Right to Left
for(int i = 0 + bias ; i < size - 1 - bias; i++) {
printArray[printCounter++] = input[i][loop2Column];
}
// Horizontal Right to Left
for(int i = size - 1 - bias ; i > 0 + bias; i--) {
printArray[printCounter++] = input[loop3Row][i];
}
// Vertical Left To Right
for(int i = size - 1 - bias; i > 0 + bias; i--) {
printArray[printCounter++] = input[i][loop4Column];
}
if( (size % 2) == 1) {
printArray[printCounter] = input[numIterations][numIterations];
}
loop1Row++;
loop2Column--;
loop3Row--;
loop4Column++;
bias++;
}
System.out.println(Arrays.toString(printArray));
}
}