Accname
2D-Graphics enthusiast
- Reaction score
- 1,462
Here is the code for TWV's weird number square thingy: (Java)
Code:
public class WeirdNumberSquareThingy {
public static void main(String[] args) {
System.out.println(new WeirdNumberSquareThingy(5));
/* Prints:
[ 1 | 2 | 6 | 7 | 15]
[ 3 | 5 | 8 | 14 | 16]
[ 4 | 9 | 13 | 17 | 22]
[ 10 | 12 | 18 | 21 | 23]
[ 11 | 19 | 20 | 24 | 25]
*/
}
private final int[] table;
private final int size;
public WeirdNumberSquareThingy(int size) {
this.size = size;
table = new int[size * size];
int num = 1;
int steps = 1;
int x = 0;
int y = 0;
boolean growing = true;
while (num <= table.length) {
for (int i = 1; i < steps; i++) {
set(x, y, num++);
if (steps % 2 == 1) {
x += 1;
y -= 1;
} else {
x -= 1;
y += 1;
}
}
if (steps == size) {
growing = false;
}
set(x, y, num++);
if (growing == (steps % 2 == 1)) {
x += 1;
} else {
y += 1;
}
if (growing) {
steps++;
} else {
steps--;
}
}
}
private void set(int x, int y, int number) {
table[x + y * size] = number;
}
public int get(int x, int y) {
return table[x + y * size];
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (int y = 0; y < size; y++) {
sb.append("[ ");
for (int x = 0; x < size; x++) {
int num = get(x, y);
if (num < 10) {
sb.append(" ");
}
sb.append(num);
if (x != size -1) {
sb.append(" | ");
}
}
sb.append("]\n");
}
return sb.toString();
}
}
Last edited: