プロダクションスクリュー2 D配列
6854 ワード
public class SpiralArray {
public static int[][] generateSpiralArray(final int x, final int y) {
int[][] blanks = new int[x][y];
int direct = 0;
int num = 0;
int posX = 0, posY = -1;
int widthlen = y;
int heightlen = x;
int xTimes = heightlen;
int yTimes = widthlen;
while (true) {
if (num == x * y)
break;
num++;
switch (direct) {
case 0:
if (--yTimes == 0) {
direct = 1;
heightlen--;
posY++;
xTimes = heightlen;
break;
}
posY++;
break;
case 1:
if (--xTimes == 0) {
direct = 2;
widthlen--;
posX++;
yTimes = widthlen;
break;
}
posX++;
break;
case 2:
if (--yTimes == 0) {
direct = 3;
heightlen--;
posY--;
xTimes = heightlen;
break;
}
posY--;
break;
case 3:
if (--xTimes == 0) {
direct = 0;
widthlen--;
posX--;
yTimes = widthlen;
break;
}
posX--;
break;
}
blanks[posX][posY] = num;
printArray(blanks, x, y);
}
return blanks;
}
priavte static void printArray(final int[][] array, final int x, final int y) {
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
System.out.printf("%-5d", blanks[i][j]);
}
System.out.println();
}
try { Thread.sleep(100); } catch (InterruptedException e) {} System.out.println();
}
public static void main(String[] args) {
int x = 5, y = 4;
int[][] array = generateSpiralArray(x, y);
printArray(array, x, y);
}
}