Skip to content

Instantly share code, notes, and snippets.

@tommyettinger
Created October 26, 2016 01:42
Show Gist options
  • Save tommyettinger/61221f4ced113f5a1daf4d56d617c038 to your computer and use it in GitHub Desktop.
Save tommyettinger/61221f4ced113f5a1daf4d56d617c038 to your computer and use it in GitHub Desktop.
Select a random true position in a boolean[][] that is not in a specific rectangle
// map can use [y][x] indexing and the names will make sense here,
// or [x][y] indexing and it will work but be named oddly and the
// Vector2 returned will be using (y, x) order.
public static Vector2 selectRandom(boolean[][] map, Random random, int xMinVisible, int xMaxVisible, int yMinVisible, int yMaxVisible)
{
int ct = 0, height = map.length, width = map[0].length;
int[] rowCounts = new int[height];
for(int y = 0; y < height; y++)
{
if(y >= yMinVisible && y <= yMaxVisible)
{
for(int x = 0; x < xMinVisible && x < width; x++)
{
if(map[y][x]) ct++;
}
for(int x = xMaxVisible + 1; x < width; x++)
{
if(map[y][x]) ct++;
}
}
else
{
for(int x = 0; x < width; x++)
{
if(map[y][x]) ct++;
}
}
if(y == 0)
rowCounts[y] = ct;
else if(y > 0 && ct > rowCounts[y-1])
rowCounts[y] = ct;
//otherwise it stays 0
}
int pos = random.nextInt(ct);
if(pos < rowCounts[0])
{
for(int x = 0; x < width; x++)
{
if(map[y][x] && --ct == pos)
return new Vector2(x, 0);
}
}
int stopper = 0;
for(int y = 1; y < height; y++)
{
if((ct = rowCounts[y]) > pos)
{
stopper = rowCounts[y-1];
for(int x = 0; x < width && ct > stopper; x++)
{
if(map[y][x] && --ct == pos)
{
return new Vector2(x, y)
}
}
}
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment