Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class SA {
- /**
- * Print out a square array with numbers filling the array diagonally (moving northeast, wrapping
- * towards the top left of the array).
- * See a diagram here: http://imgur.com/sLOfNNn
- *
- * Input:
- * dim = non-zero-based dimensions of the grid to return.
- * startX, startY = a point within the grid, not zero-based; return zeroed-out grid if it's outside
- * startCount = an integer to begin counting from
- *
- * Example:
- * dim = 3
- * startX, startY = 3,2
- * startCount = 12
- * [ 18, 17, 15 ]
- * [ 16, 14, 12 ]
- * [ 13, 20, 19 ]
- */
- public static void main(String[] args) {
- int dim = 5; // not zero-based
- int startX = 2; // not zero-based
- int startY = 4; // not zero-based
- int startCount = 200;
- int currentCount = startCount;
- int currX = startX-1;
- int currY = startY-1;
- int[][] grid = new int[dim][dim];
- // Check input for errors
- // If dim <= 0
- if (dim <=0) {
- System.out.println("Error! Dimensions of the grid must be 1x1 or larger.");
- System.exit(0);
- }
- // 1x1 grid
- if (dim == 1) {
- System.out.println("Result:");
- System.out.println(startCount);
- System.exit(0);
- }
- // If startX or startY are outside the grid
- if ((startX > dim) || (startY > dim) || startX <0 || startY <0) {
- System.out.println("Error! StartX and startY must be within the grid.");
- System.exit(0);
- }
- // Step through every element of the array
- while (currentCount < (startCount + (dim)*(dim) )) {
- // insert the number in the current spot, and increment it
- System.out.println("Inserting " + currentCount + " at X, Y = " + currX + ", " + currY);
- grid[currX][currY] = currentCount++;
- // now increment currX and currY
- currX += 1;
- currY -= 1;
- // if either is outside the bounds of the grid, find a new currX & currY
- if ((currX == dim) || (currY < 0))
- {
- // move the other way diagonally until either X or Y is off the grid
- while (currX!=-1 && currY != dim) {
- currX-=1;
- currY+=1;
- }
- } else {
- continue;
- }
- System.out.println("Need a new start point. We moved off the grid to: " + currX + ", " + currY);
- // if we were in the ULH corner, swap to the BRH corner
- if (currX == -1 && currY ==1) {
- currX = dim-1;
- currY = dim-1;
- } else {
- if (currY == dim) { // we were on the bottom row
- currY -=1;
- if (currX == -1) { // BLH corner case
- currX +=1;
- currY -=1;
- continue;
- } else {continue;}
- } // we were on the first column
- currX +=1;
- currY -=2;
- }
- }
- // Print out results
- System.out.println("Result, with currentCount = " + currentCount + " :");
- for (int y = 0; y<dim; y++) {
- for (int x = 0; x<dim; x++) {
- System.out.print(grid[x][y]);
- if (x < dim-1) System.out.print(", ");
- }
- System.out.println();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement