Created
October 27, 2019 18:46
-
-
Save jkoppel/b76daa83f0767737155d39b88a2801d3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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