Last active
June 22, 2018 10:33
-
-
Save sangmoon/e5c5762fe9152517646b6a8bc83b3c96 to your computer and use it in GitHub Desktop.
Fill the number in 2d array circulating in a spiral.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.sangmoon.square; | |
public class Square { | |
public static void main(String arg[]){ | |
int N = Integer.parseInt(arg[0]); | |
int[][] map = new int[N][N]; | |
Square s = new Square(); | |
s.solve(0, 0, map, 1, N); | |
for (int i=0; i< N; i++){ | |
for (int j =0; j<N; j++){ | |
System.out.format("%02d ", map[i][j]); | |
} | |
System.out.println(); | |
} | |
} | |
public void solve(int startX, int startY, int[][] map, int k, int n){ | |
int posX = startX; | |
int posY = startY; | |
int idx = 1; | |
map[posX][posY] = k; | |
if (n == 1) | |
return; | |
idx++; | |
k++; | |
Direction d = Direction.RIGHT; | |
Counter c = new Counter(n-1); | |
while(idx <= 4*n -4){ | |
posX += d.getX(); | |
posY += d.getY(); | |
map[posX][posY] = k; | |
idx++; | |
k++; | |
c.count(); | |
if (c.getCount() == n - 1){ | |
switch (d){ | |
case RIGHT: | |
d = Direction.DOWN; | |
break; | |
case DOWN: | |
d = Direction.LEFT; | |
break; | |
case LEFT: | |
d = Direction.UP; | |
break; | |
default: | |
System.out.println("nonono"); | |
} | |
} | |
} | |
if ( n == 2 ){ | |
return; | |
} else { | |
solve(posX, posY +1, map, k, n -2 ); | |
} | |
} | |
} | |
enum Direction { | |
RIGHT(0, 1), LEFT(0, -1), DOWN(1, 0), UP(-1, 0); | |
public int getX() { | |
return x; | |
} | |
public int getY() { | |
return y; | |
} | |
private int x; | |
private int y; | |
Direction(int x, int y){ | |
this.x = x; | |
this.y = y; | |
} | |
} | |
class Counter{ | |
private int initCount; | |
private int count; | |
Counter(int n){ | |
initCount = n; | |
count = n; | |
} | |
public void count(){ | |
count --; | |
if (count == 0) | |
count = initCount; | |
return; | |
} | |
public int getCount(){ | |
return count; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment