Skip to content

Instantly share code, notes, and snippets.

@KatrinaHoffert
Created July 9, 2015 01:59
Show Gist options
  • Save KatrinaHoffert/bb67af740626f594fe5f to your computer and use it in GitHub Desktop.
Save KatrinaHoffert/bb67af740626f594fe5f to your computer and use it in GitHub Desktop.
import java.awt.Point;
public class Main {
public static int[][] create2dArray(int size) {
int[][] array = new int[size][size];
for(int row = 0; row < size; ++row) {
for(int col = 0; col < size; ++col) {
array[row][col] = (col + 1) + size * row;
}
}
return array;
}
public static void print2dArray(int[][] array) {
for(int[] row : array) {
for(int element : row) {
System.out.print(element + "\t");
}
System.out.println();
}
}
public static int[][] spiralizeArray(int[][] array) {
int arraySize = array[0].length;
int[][] spiralArray = new int[arraySize][arraySize];
Point position = new Point((arraySize - 1) / 2, (arraySize - 1) / 2);
Direction directionToMove = Direction.RIGHT;
int distanceToMove = 1;
int totalMovementInDirection = 1;
for(int i = 0; i < arraySize * arraySize; ++i) {
// Uncomment this line to see the position we're at in the spiral
//System.out.println("Spiral: (" + position.x + ", " + position.y + ")");
// Uncomment this line to see the position we're at in the original
//System.out.println("Original: (" + (i / arraySize) + ", " + (i % arraySize) + ")");
// Copy the ith value to the position placement
spiralArray[position.x][position.y] = array[i / arraySize][i % arraySize];
// We've exhausted a move in that direction
--distanceToMove;
// If we're changing from moving up or down, then the distance we move
// will increase.
if(distanceToMove == 0 && (directionToMove == Direction.UP ||
directionToMove == Direction.DOWN)) {
++totalMovementInDirection;
}
// Figure out which way to move in. While we're at it, figure out the
// new direction if we've reached the end of where to move
if(directionToMove == Direction.UP) {
position.translate(-1, 0);
if(distanceToMove == 0) directionToMove = Direction.RIGHT;
}
else if(directionToMove == Direction.DOWN) {
position.translate(1, 0);
if(distanceToMove == 0) directionToMove = Direction.LEFT;
}
else if(directionToMove == Direction.LEFT) {
position.translate(0, -1);
if(distanceToMove == 0) directionToMove = Direction.UP;
}
else {
position.translate(0, 1);
if(distanceToMove == 0) directionToMove = Direction.DOWN;
}
// And if we reached 0 distance to move, that gets reset
if(distanceToMove == 0) {
distanceToMove = totalMovementInDirection;
}
}
return spiralArray;
}
private enum Direction { UP, DOWN, LEFT, RIGHT }
public static void main(String[] args) {
int[][] array = create2dArray(4);
int[][] spiral = spiralizeArray(array);
System.out.println("ORIGINAL:");
print2dArray(array);
System.out.println("SPIRAL:");
print2dArray(spiral);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment