Skip to content

Instantly share code, notes, and snippets.

@jkoppel
Created Oct 27, 2019
Embed
What would you like to do?
private static class Vec {
int x, y;
public Vec(int x, int y) { this.x = x; this.y = y; }
public Vec add(Vec oth) { return new Vec(x+oth.x, y+oth.y); }
public Vec rot90CW() { return new Vec(y, -x); }
public int infDist(Vec oth) { return Math.max(x-oth.x, y-oth.y); }
public boolean equals....
}
// Returns spiral pattern in a (2n+1) * (2n+1) array
/*
.......
...***.
...*.*.
...*.*.
.....*.
.*****.
.......
*/
public boolean[][] makeSpiral(int n) {
int dim = 2*n + 1;
boolean[][] board = new boolean[dim][dim]; // initialized to all false
Vec cent = new Vec(dim / 2, dim / 2);
Vec pos = cent;
Vec dir = new Vec(0, -1);
int curRadius = 2;
board[pos.y][pos.x] = true;
while (radius <= n) {
while (!pos.equals(cent.add(new Vec(curRadius, curRadius)))) {
pos = pos.add(dir);
board[pos.y][pos.x] = true;
if (pos.add(dir).infDist(cent) > radius) {
dir = dir.rot90CW();
}
}
radius += 2;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment