Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.Point;
- /**
- * Oh, you thought creating squares is easy?!
- * Not here, no way!
- *
- */
- public class Challenge1 {
- public static void main(String[] args) {
- // I'm too lazy to check if arguments are formatted correctly
- // do that yourself!
- int size = Integer.parseInt(args[0]);
- if(size % 2 == 0 || size < 0) {
- System.err.println("Input must be an odd positive number");
- System.exit(1);
- }
- printSquare(size);
- }
- /**
- * Print sweet squares such as this
- *
- * 111 112 113 114 115 116 117 118 119 120 121
- * 110 73 74 75 76 77 78 79 80 81 82
- * 109 72 43 44 45 46 47 48 49 50 83
- * 108 71 42 21 22 23 24 25 26 51 84
- * 107 70 41 20 7 8 9 10 27 52 85
- * 106 69 40 19 6 1 2 11 28 53 86
- * 105 68 39 18 5 4 3 12 29 54 87
- * 104 67 38 17 16 15 14 13 30 55 88
- * 103 66 37 36 35 34 33 32 31 56 89
- * 102 65 64 63 62 61 60 59 58 57 90
- * 101 100 99 98 97 96 95 94 93 92 91
- *
- * whaaaaat how did he do that? will this get me all the ladies? let's wait and see!
- *
- * @param size
- */
- private static void printSquare(int size) {
- // initialize arrays
- int[][] square = new int[size][];
- for(int line = 0; line < size; line++) {
- square[line] = new int[size];
- }
- // current position, direction to walk to
- Point pos = new Point(size / 2, size / 2);
- Point dir = new Point(1, 0);
- // change direction based on step count
- // first two times turn right on every single step
- // then two times on every second step (done through incrementing stepReset by 2)
- // then two times on every third step...
- int stepReset = 2;
- int stepCount = stepReset;
- for(int num = 1; num <= size * size; num++) {
- square[pos.y][pos.x] = num;
- pos.translate(dir.x, dir.y);
- // if step count is half of stepReset or 0, turn right
- stepCount--;
- if(stepCount % (stepReset / 2) == 0) {
- int tmp = dir.x;
- dir.x = -dir.y;
- dir.y = tmp;
- // turned right twice with same length
- // add 1 to the amount of steps it takes to turn right again
- if(stepCount == 0) {
- stepReset += 2;
- stepCount = stepReset;
- }
- }
- }
- // right align numbers. if longest number has three digits, 1 will be displayed as " 1"
- String digits = "%" + ((int) Math.log10(size * size) + 1) + "d ";
- for(int[] y : square) {
- for(int x : y) {
- System.out.printf(digits, x);
- }
- System.out.println();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement