我有一个坐标系,基本上代表了屏幕。 我有位置的任意量。例如。:
population = [
{x: 100.44, 200.54},
{x: 123.45, 678.9},
{x: 1300.23, 435.81},
{x: 462.23, 468.37},
{x: 956.58, 385.38},
];
我正在寻找的是找到最无人居住点的算法。
白色的小圆圈代表的人口,并且显得很无人居住给我的红叉标志点:
我的目标是运行随机所有这些白色小圈移动到任意方向,并尽快为圆已经离开,这样大空的空间量减少得到它应该得到瞬间移动到最无人居住的现场画面的动画。
我试图通过计算距离从每一个整数之和协调,每一个圆,然后选择坐标具有最高的距离和实现这一点。这本身似乎是相当CPU密集型了,但我注意到,该算法导致的圆圈瞬移到我的坐标系的边界。所以,我还添加了从每个整数的距离之和协调,每一个边境整数坐标。在这一点上,脚本基本上冻结。因此,这是绝对不正确的方法。
我跑出来的想法。我想我并不需要一个完美的算法,而是一个与精度和性能之间的健康平衡。最后,我希望能够在1920×1080的帆布每秒多次运行该算法与这些小环的约80。理想情况下,算法将有一个参数调整精度,从而多少CPU时,就会使用。
这是上面提到的我的方法。我注释掉导致该脚本只是冻结行:
let circles = [
{x: 60.44, y: 190.54},
{x: 103.45, y: 18.9},
{x: 390.23, y: 135.81},
{x: 302.23, y: 28.37},
{x: 56.58, y: 85.38},
]
function getDistance(p1, p2) {
return Math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2)
}
function drawCircle(ctx,x,y,r,c) {
ctx.beginPath()
ctx.arc(x, y, r, 0, 2 * Math.PI, false)
ctx.fillStyle = c
ctx.fill()
}
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext("2d")
let highestDistanceSum = 0
let coordWithHighestDistanceSum
for (let x=0; x<canvas.width; x++) {
for (let y=0; y<canvas.height; y++) {
let canvasCoord = {x: x, y: y}
let distanceSum = 0
for (let circle of circles) {
distanceSum += getDistance(canvasCoord, circle)
}
/*
// Pretend as if every pixel on the border is a circle
// Causes massive CPU usage
for (let x2=0; x<canvas.width; x2++) {
distanceSum += getDistance(canvasCoord, {x: x2, y: 0})
distanceSum += getDistance(canvasCoord, {x: x2, y: canvas.height})
}
for (let y2=0; y<canvas.height; y2++) {
distanceSum += getDistance(canvasCoord, {x: 0, y: y2})
distanceSum += getDistance(canvasCoord, {x: canvas.width, y: y2})
}
*/
if (distanceSum > highestDistanceSum) {
coordWithHighestDistanceSum = canvasCoord
highestDistanceSum = distanceSum
}
}
}
for (let p of circles) {
drawCircle(ctx, p.x, p.y, 3, 'black')
}
drawCircle(ctx, coordWithHighestDistanceSum.x, coordWithHighestDistanceSum.y, 5, 'red')
<canvas id="canvas" width="400" height="200" style="border:1px solid #d3d3d3;"></canvas>
(因为它是白色的点黑色帆布,我会打电话给白点星为便于区别)
首先,你的解决方案似乎并不符合您的标准。你不需要有距离的,以全明星最大的一笔点。您需要最远的距离点到其最近的恒星。
为了详细说明,让我们如这样说,那里是在中心一星级和大量的恒星一定距离中心的情况:
“最大距离之和”的方法可能会在红色圆圈给出一个点的地方(这是太接近甚至重合的中心星),而你想要的东西会更喜欢在绿圈的东西:
考虑到这一点:
在“合理规模”的部分是非常重要的性能,明智的。您所使用的分辨率为1920x1080,这是方式在我看来过于细粒度。为了得到视觉上令人愉悦足够结果,48x30的分辨率,甚至32x20将绰绰有余。
其结果将是这样的:
这里有一个还是大问题:红色共青广场位于底部边缘!
转出边和角广场有“作弊”优于中心COORDS,因为有朝向一侧无星级(甚至三面,对角区域)。因此,它很可能是一个角落和边缘方将有最大距离的任何明星。
这是不是很视觉愉悦你的,呃,艺术作品?因此,我们可以通过过滤出的结果是一定的填充内骗了一下。幸运的是BFS”结果默认排序,这样我们就可以遍历结果,直到我们找到一个适合所需的区域内。
以下是评论的完整代码。即使距离图可见,整个过程需要20毫秒,这应该是足够用于一块的WebGL(其运行@最大30fps的〜为33ms /帧)
该解决方案也将照顾极少数情况下几颗搬出绑定在相同的帧。在这种情况下,刚刚从获取BFS的结果几个不同COORDS。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body style="margin: 0; padding: 0;">
<canvas id="canvas" style="display: block;"></canvas>
<script>
// higher GRID_WIDTH = better result, more calculation time
// We will caculate gridHeight later based on window size
const GRID_WIDTH = 48;
const GRID_PADDING = 3;
const heatMapColors = [
'#ffffff',
'#ffdddd',
'#ffbbbb',
'#ff9999',
'#ff7777',
'#ff5555',
'#ff3333',
'#ff0000'
]
const init = () => {
var circles = [];
for (var i = 0; i < 90; i++) {
circles.push({
x: Math.random() * window.innerWidth,
y: Math.random() * window.innerHeight
});
}
const canvas = document.getElementById('canvas')
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const ctx = canvas.getContext("2d");
const cellSize = window.innerWidth / GRID_WIDTH;
const gridHeight = Math.ceil(canvas.height / cellSize);
update(ctx, circles, GRID_WIDTH, gridHeight, cellSize);
}
const update = (ctx, circles, gridWidth, gridHeight, cellSize) => {
const start = new Date();
// Perform a BFS from all stars to find distance of each rect from closest star
// After BFS visitedCoords will be an array of all grid rect, with distance-from-star (weight) sorted in ascending order
var bfsFrontier = getGridCoordOfStars(circles, cellSize).map(coord => ({ ...coord, weight: 0 }));
var visitedCoords = [...bfsFrontier];
while (bfsFrontier.length > 0) {
const current = bfsFrontier.shift();
const neighbors = getNeighbors(current, gridWidth, gridHeight);
for (let neighbor of neighbors) {
if (visitedCoords.findIndex(weightedCoord => coordsEqual(weightedCoord, neighbor)) === -1) {
visitedCoords.push(neighbor);
bfsFrontier.push(neighbor);
}
}
}
// Visualize heatmap
for (let coord of visitedCoords) {
drawRect(ctx, coord.x * cellSize, coord.y * cellSize, cellSize, cellSize, heatMapColors[Math.min(coord.weight, heatMapColors.length - 1)]);
}
const emptiestCoord = getLastCoordWithinPadding(visitedCoords, gridWidth, gridHeight, GRID_PADDING);
const emptiestPosition = {
x: (emptiestCoord.x + 0.5) * cellSize,
y: (emptiestCoord.y + 0.5) * cellSize
}
drawCircle(ctx, emptiestPosition.x, emptiestPosition.y, 5, 'yellow');
for (let p of circles) {
drawCircle(ctx, p.x, p.y, 3, 'black')
}
console.log(`Processing time: ${new Date().getTime() - start.getTime()} ms`);
}
const drawCircle = (ctx, x, y, r, c) => {
ctx.beginPath()
ctx.arc(x, y, r, 0, 2 * Math.PI, false)
ctx.fillStyle = c
ctx.fill()
}
const drawRect = (ctx, x, y, width, height, c) => {
ctx.beginPath();
ctx.rect(x, y, width, height);
ctx.fillStyle = c;
ctx.fill();
}
// Convert star position to grid coordinate
// Don't need to worry about duplication, BFS still work with duplicates
const getGridCoordOfStars = (stars, cellSize) =>
stars.map(star => ({
x: Math.floor(star.x / cellSize),
y: Math.floor(star.y / cellSize)
}))
const coordsEqual = (coord1, coord2) => coord1.x === coord2.x && coord1.y === coord2.y;
const getNeighbors = (weightedCoord, gridWidth, gridHeight) => {
var result = [];
if (weightedCoord.x > 0) result.push({ x: weightedCoord.x - 1, y: weightedCoord.y, weight: weightedCoord.weight + 1 })
if (weightedCoord.x < gridWidth - 1) result.push({ x: weightedCoord.x + 1, y: weightedCoord.y, weight: weightedCoord.weight + 1 })
if (weightedCoord.y > 0) result.push({ x: weightedCoord.x, y: weightedCoord.y - 1, weight: weightedCoord.weight + 1 })
if (weightedCoord.y < gridHeight - 1) result.push({ x: weightedCoord.x, y: weightedCoord.y + 1, weight: weightedCoord.weight + 1 })
return result;
}
// loop through a BFS result from bottom to top and return first occurence inside padding
const getLastCoordWithinPadding = (coords, gridWidth, gridHeight, padding) => {
for (let i = coords.length - 1; i > 0; i--) {
const coord = coords[i];
if (
coord.x >= padding
&& coord.x < gridWidth - padding - 1
&& coord.y >= padding
&& coord.y < gridHeight - padding - 1
) return coord;
}
// This does not happen with current logic, but I leave it here to catch future code changes
return coords[coords.length - 1];
}
init();
</script>
</body>
</html>
编辑:
我刚读@ArneHugo的答案,我看到与明星一起加入边框,BFS开始位置也能发挥作用。这是稍微慢一些,但给更令人高兴的结果。
这里是实现他们的想法另一个版本:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body style="margin: 0; padding: 0;">
<canvas id="canvas" style="display: block;"></canvas>
<script>
const GRID_WIDTH = 48; // We will caculate gridHeight based on window size
const heatMapColors = [
'#ffffff',
'#ffdddd',
'#ffbbbb',
'#ff9999',
'#ff7777',
'#ff5555',
'#ff3333',
'#ff0000'
]
const init = () => {
var circles = [];
for (var i = 0; i < 90; i++) {
circles.push({
x: Math.random() * window.innerWidth,
y: Math.random() * window.innerHeight
});
}
const canvas = document.getElementById('canvas')
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const ctx = canvas.getContext("2d");
const cellSize = window.innerWidth / GRID_WIDTH;
const gridHeight = Math.ceil(canvas.height / cellSize); // calculate gridHeight
// cache border coords array since it's never changed
const borderCoords = getBorderCoords(GRID_WIDTH, gridHeight);
update(ctx, circles, GRID_WIDTH, gridHeight, cellSize, borderCoords);
}
const update = (ctx, circles, gridWidth, gridHeight, cellSize, borderCoords) => {
const start = new Date();
// Perform a BFS from all stars to find distance of each rect from closest star
// After BFS visitedCoords will be an array of all grid rect, with distance-from-star (weight) sorted in ascending order
var bfsFrontier = borderCoords.concat(
getGridCoordOfStars(circles, cellSize).map(coord => ({ ...coord, weight: 0 }))
);
var visitedCoords = [...bfsFrontier];
while (bfsFrontier.length > 0) {
const current = bfsFrontier.shift();
const neighbors = getNeighbors(current, gridWidth, gridHeight);
for (let neighbor of neighbors) {
if (visitedCoords.findIndex(weightedCoord => coordsEqual(weightedCoord, neighbor)) === -1) {
visitedCoords.push(neighbor);
bfsFrontier.push(neighbor);
}
}
}
// Visualize heatmap
for (let coord of visitedCoords) {
drawRect(ctx, coord.x * cellSize, coord.y * cellSize, cellSize, cellSize, heatMapColors[Math.min(coord.weight, heatMapColors.length - 1)]);
}
const emptiestCoord = visitedCoords[visitedCoords.length - 1];
const emptiestPosition = {
x: (emptiestCoord.x + 0.5) * cellSize,
y: (emptiestCoord.y + 0.5) * cellSize
}
drawCircle(ctx, emptiestPosition.x, emptiestPosition.y, 5, 'yellow');
for (let p of circles) {
drawCircle(ctx, p.x, p.y, 3, 'black')
}
console.log(`Processing time: ${new Date().getTime() - start.getTime()} ms`);
}
const drawCircle = (ctx, x, y, r, c) => {
ctx.beginPath()
ctx.arc(x, y, r, 0, 2 * Math.PI, false)
ctx.fillStyle = c
ctx.fill()
}
const drawRect = (ctx, x, y, width, height, c) => {
ctx.beginPath();
ctx.rect(x, y, width, height);
ctx.fillStyle = c;
ctx.fill();
}
const getBorderCoords = (gridWidth, gridHeight) => {
var borderCoords = [];
for (var x = 0; x < gridWidth; x++) {
for (var y = 0; y < gridHeight; y++) {
if (x === 0 || y === 0 || x === gridWidth - 1 || y === gridHeight - 1) borderCoords.push({ x, y, weight: 0 })
}
}
return borderCoords;
}
// Convert star position to grid coordinate and filter out duplicates
const getGridCoordOfStars = (stars, cellSize) => stars.map(star => ({
x: Math.floor(star.x / cellSize),
y: Math.floor(star.y / cellSize)
}))
const uniqueCoord = (arr) => arr.filter((candidate, index) => arr.findIndex(item => coordsEqual(item, candidate)) === index);
const coordsEqual = (coord1, coord2) => coord1.x === coord2.x && coord1.y === coord2.y;
const getNeighbors = (weightedCoord, gridWidth, gridHeight) => {
var result = [];
if (weightedCoord.x > 0) result.push({ x: weightedCoord.x - 1, y: weightedCoord.y, weight: weightedCoord.weight + 1 })
if (weightedCoord.x < gridWidth - 1) result.push({ x: weightedCoord.x + 1, y: weightedCoord.y, weight: weightedCoord.weight + 1 })
if (weightedCoord.y > 0) result.push({ x: weightedCoord.x, y: weightedCoord.y - 1, weight: weightedCoord.weight + 1 })
if (weightedCoord.y < gridHeight - 1) result.push({ x: weightedCoord.x, y: weightedCoord.y + 1, weight: weightedCoord.weight + 1 })
return result;
}
init();
</script>
</body>
</html>
下面是一个例子,但我认为,如果你有更多的圈子里可能会更有趣。
[canvas.width - coord.x, coord.x - 0, canvas.height - coord.y, coord.y -0]
)计数,与距离每个现有圆一起进行。(我也变成一个更实用的风格,因为我发现更容易,虽然这是没有必要的。)
const numberOfCirclesToGetDistanceTo = 2
let circles = [
{x: 60.44, y: 190.54},
{x: 103.45, y: 18.9},
{x: 390.23, y: 135.81},
{x: 302.23, y: 28.37},
{x: 56.58, y: 85.38},
]
function getDistance(p1, p2) {
return Math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2)
}
function drawCircle(ctx,x,y,r,c) {
ctx.beginPath()
ctx.arc(x, y, r, 0, 2 * Math.PI, false)
ctx.fillStyle = c
ctx.fill()
}
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext("2d")
function getCoordWithHighestDistanceSum() {
const xList = Array(canvas.width).fill().map((_, index) => index)
const yList = Array(canvas.height).fill().map((_, index) => index)
const coords = xList.flatMap(x => yList.reduce((coords, y) => coords.concat({ x, y }), []))
const ascending = (a, b) => a - b
const sumTotal = (sum, next) => sum + next
const coordsWithDistance = coords.map(coord => {
const distances = [
...circles.map(circle => getDistance(coord, circle)),
...[canvas.width - coord.x, coord.x - 0, canvas.height - coord.y, coord.y -0],
]
return {
coord,
dist: distances
.sort(ascending)
.slice(0, numberOfCirclesToGetDistanceTo)
.reduce(sumTotal, 0)
}
})
return coordsWithDistance
.sort((a, b) => b.dist - a.dist)
[0].coord
}
const coordWithHighestDistanceSum = getCoordWithHighestDistanceSum()
for (let p of circles) {
drawCircle(ctx, p.x, p.y, 3, 'black')
}
drawCircle(ctx, coordWithHighestDistanceSum.x, coordWithHighestDistanceSum.y, 5, 'red')
<canvas id="canvas" width="400" height="200" style="border:1px solid #d3d3d3;"></canvas>
这是一个互动性更强的版本,所以你可以测试它是如何工作的。正如你所看到的,大部分的时间,最少的人口稠密区是沿边缘时随机生成的其他各界。此外,更圆检查的距离,当你算上,你越倾向于去朝边缘和采摘人口最少的密集区域时的角落。
用于发现至少居民区的逻辑是相同的在原始溶液。
let circles = []
let coordWithHighestDistanceSum = void 0
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext("2d")
const xList = Array(canvas.width).fill().map((_, index) => index)
const yList = Array(canvas.height).fill().map((_, index) => index)
const coords = xList.flatMap(x => yList.reduce((coords, y) => coords.concat({ x, y }), []))
function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height)
function drawCircle(ctx,x,y,r,c) {
ctx.beginPath()
ctx.arc(x, y, r, 0, 2 * Math.PI, false)
ctx.fillStyle = c
ctx.fill()
}
circles.forEach(circle => drawCircle(ctx, circle.x, circle.y, 3, 'black'))
if (coordWithHighestDistanceSum) {
drawCircle(ctx, coordWithHighestDistanceSum.x, coordWithHighestDistanceSum.y, 5, 'red')
}
}
function generateCircles() {
const nofCircles = Number(document.getElementById('nofCircles').value)
const randomCoord = () => coords[Math.floor(Math.random() * coords.length)]
circles = Array(nofCircles).fill().map(randomCoord)
findLeastPopulatedCoordinate()
render()
}
function findLeastPopulatedCoordinate() {
const nofCirclesToSumDistanceTo = Number(document.getElementById('nofCirclesToSumDistanceTo').value)
const ascending = (a, b) => a - b
const sumTotal = (sum, next) => sum + next
function getDistance(p1, p2) {
return Math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2)
}
coordWithHighestDistanceSum = coords
.map(coord => ({
coord,
dist: []
.concat(circles.map(circle => getDistance(coord, circle)))
.concat([canvas.width - coord.x, coord.x - 0, canvas.height - coord.y, coord.y -0])
.sort(ascending)
.slice(0, nofCirclesToSumDistanceTo)
.reduce(sumTotal, 0)
}))
.sort((a, b) => b.dist - a.dist)
[0].coord
render()
}
generateCircles()
findLeastPopulatedCoordinate()
<div>
<label>Number of circles</label>
<input type="number" id="nofCircles" value="30" />
</div>
<div>
<label>Number of circles to sum distance to</label>
<input type="number" id="nofCirclesToSumDistanceTo" value="1" />
</div>
<button onclick="generateCircles()">Generate circles</button>
<button onclick="findLeastPopulatedCoordinate()">Find least populated coordinate</button>
<canvas id="canvas" width="400" height="200" style="border:1px solid #d3d3d3;"></canvas>
你可以把画布的具有1080×1920列和行,与代表空白区和x列0 1S初始化的矩阵,y行代表在该坐标点。现在,你需要找到一个二元矩阵的最大空矩形。
这Dr. Dobb's article包含的最快算法的问题之一。你可以在互联网上找到一个JavaScript实现或实现它自己。
您也可以考虑找的最大空方。
var canvas = document.querySelector("#canvas-1");
var rctx = canvas.getContext("2d");
var ncols = canvas.width;
var nrows = canvas.height;
var npoints = +canvas.dataset.points;
var matrix = Array(nrows).fill(0).map(function() {
return Array(ncols).fill(1);
});
var i, x, y, t0, t1, maxrect, maxsquare;
/*
* For consistency with algorithms, the matrix is initialized with 1s
* representing the blank area and the points are represented with 0s
*/
for (i = 0; i < npoints; i++) {
x = Math.floor(Math.random() * ncols);
y = Math.floor(Math.random() * nrows);
matrix[y][x] = 0;
}
t0 = new Date();
maxrect = maximalRectangle(matrix);
t1 = new Date();
console.log("Rectangle found in %dms", t1 - t0);
t0 = new Date();
maxsquare = maximalSquare(matrix);
t1 = new Date();
console.log("Square found in %dms", t1 - t0);
/*
* Render the results
*/
rctx.fillStyle = "rgba(255,0,0,.5)";
rctx.fillRect(maxrect.left, maxrect.top, maxrect.right - maxrect.left + 1, maxrect.bottom - maxrect.top + 1);
rctx.fillStyle = "rgba(0,0,255,.5)";
rctx.fillRect(maxsquare.left, maxsquare.top, maxsquare.right - maxsquare.left + 1, maxsquare.bottom - maxsquare.top + 1);
rctx.fillStyle = "rgb(255,255,255)";
for (y = 0; y < nrows; y++) {
for (x = 0; x < ncols; x++) {
if (matrix[y][x] === 0) {
rctx.fillRect(x, y, 1, 1);
}
}
}
/*
* implementation of this answer:
* https://stackoverflow.com/a/20039017/87015
*/
function maximalRectangle(matrix) {
var best_area = 0;
var best_rect = {};
var M = matrix[0].length;
var N = matrix.length;
var c = Array(M + 1).fill(0);
var s = [];
var m, n, open_width, area, prev;
for (n = 0; n < N; n++) {
for (m = 0; m < M; m++) {
if (matrix[n][m] === 0) {
c[m] = 0;
} else {
c[m]++;
}
}
open_width = 0;
for (m = 0; m < M + 1; m++) {
if (c[m] > open_width) {
s.push({
m: m,
w: open_width
});
open_width = c[m];
} else if (c[m] < open_width) {
do {
prev = s.pop();
area = open_width * (m - prev.m);
if (area > best_area) {
best_area = area;
best_rect.left = prev.m;
best_rect.right = m - 1;
best_rect.top = n - open_width + 1;
best_rect.bottom = n;
}
open_width = prev.w;
} while (c[m] < open_width);
open_width = c[m];
if (open_width != 0) {
s.push(prev);
}
}
}
}
return {
area: best_area,
left: best_rect.left,
top: best_rect.top,
right: best_rect.right,
bottom: best_rect.bottom
};
}
/*
* (possibly buggy) implementation of this answer:
* https://stackoverflow.com/a/1726667/87015
*/
function maximalSquare(matrix) {
var best_length = 0;
var best_square = {};
var M = matrix[0].length;
var N = matrix.length;
var c = Array(M + 1).fill(0);
var n, m, temp, prev = 0;
for (n = 1; n <= N; n++) {
for (m = 1; m <= M; m++) {
temp = c[m];
if (matrix[n - 1][m - 1] === 1) {
c[m] = Math.min(Math.min(c[m - 1], prev), c[m]) + 1;
if (best_length < c[m]) {
best_length = c[m];
best_square.left = m - best_length;
best_square.right = m - 1;
best_square.top = n - best_length;
best_square.bottom = n - 1;
}
} else {
c[m] = 0;
}
prev = temp;
}
}
return {
area: best_length * best_length,
left: best_square.left,
top: best_square.top,
right: best_square.right,
bottom: best_square.bottom
};
}
<canvas id="canvas-1" width="1920" height="1080" data-points="80" style="background-color: #000;"></canvas>