Skip to content

Instantly share code, notes, and snippets.

@jkoppel
Created October 27, 2019 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkoppel/b76daa83f0767737155d39b88a2801d3 to your computer and use it in GitHub Desktop.
Save jkoppel/b76daa83f0767737155d39b88a2801d3 to your computer and use it in GitHub Desktop.
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