正の整数 N を指定すると、1 から n^2 までの数値をらせん状に表示する整数からなる正方行列 NxN を作成して返すクラスを作成します。
私のクラスでは 4 つのメソッドを取得しました。そのうちの 3 つは方向用で、spiral()
メソッドはすべての数字を適切な場所に配置する必要があります。
public static int[][] spiral(int n) {
int[][] res;
int i,j;
int num;
int direction;
/** variables initializzazion */
res=new int[n][n];
i=0;
j=0;
res[i][j]=1;
direction=0;
for(num=2; num<=n*n; num++) {
direction = updateDirection(direction, i, j, n);
if ((direction==1) || (direction==3))
i=updateRow(i, direction);
else
j=updateColoumn(j, direction);
res[i][j]=num;
}
return res;
}
悲しいことに、それを実行しようとするとArrayIndexOutOfBoundException
、res[i][j]=1;
.
配列が 1 から始まり、N*N になるように修正するにはどうすればよいですか?
編集updateDirection()
:メソッドを追加
この方法をよりよく理解するには、次の画像をご覧ください。
public static int updateDirection(int direction, int i, int j, int n) {
/** if on the secondary diagonal direction is 1 or 3 */
if(i+j==n-1)
direction++;
/** if on the lower half of the main diagonal, direction is 2 */
if(i==j && j+j>=n)
direction++;
/** if on the row below the higher half of the main diagonal, direction is 0 */
if(i==j+1 && i+j<n)
direction++;
/** in other cases, direction doesn't change */
return direction%4;
}
Edit2 :これは私のテスト方法です:
public static void testSpiral(){
for(int n=0; n<=5; n++)
System.out.println(Arrays.deepToString(spiral(n)));
}
Edit3 :updateRow()
およびupdateColoumn()
メソッドが追加されました:
public static int updateRow(int i, int direction) {
int res;
if(direction==1)
res=i+1; //moves from top to bottom
else
res = i-1; //moves from bottom to top
return res;
}
public static int updateColoumn(int j, int direction){
int res;
if(direction==0)
res=j+1; //moves from left to right
else
res=j-1; //moves from right to left
return res;