![](/img/trans.png)
[英]How to find coordinates of a point where 2 points and distance are given with Javascript
[英]JS: given a point in a 2d array and a distance, which coordinates are travelable?
給定任意大小的2D數組,如下所示:
var board = [
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0]
];
...和該數組中給定的[y] [x]點,例如:
board[3][4]
......以及它可以行進的給定數量的空間(上/下/左/右, 而不是對角線),如:
var distance = 3;
...一個函數如何循環通過2D數組並創建一個僅列出可能行進的坐標的列表?
(這是數組中給定坐標(*)的可視示例,以及周圍的可行坐標。)
0 0 0 0 0 0 0 0
0 0 0 3 0 0 0 0
0 0 3 2 3 0 0 0
0 3 2 1 2 3 0 0
3 2 1 * 1 2 3 0
0 3 2 1 2 3 0 0
0 0 3 2 3 0 0 0
0 0 0 3 0 0 0 0
參考: JS:如何通過算法突出顯示菱形選擇的x / y坐標? (之前我問過這個問題,但我無法理解如何輸入坐標並接收坐標列表)
迭代所有坐標(或子集xd,yd
... x+d,y+d
如果區域很大)。
對於每個字段,計算距離 - 在您的情況下為dx - dy
- 並且每當您找到距離> 0的點時,用它做任何您想做的事情。 否則,忽略它。 而已!
與泛洪填充方法相比,您可以獲得簡單的代碼,而且無需額外的查找表。
這是我能想到的最簡單的解決方案,它涉及從上到下,從左到右的工作, 只迭代允許移動的坐標,所以它應該非常快:
function getPossibleMoves(x, y) {
var r, c, cMax,
distance = 3,
rows = board.length,
cols = board[0].length,
rMax = Math.min(y + distance + 1, rows),
ret = [],
yOff;
// Start at the first row with a permissible move
for (r = Math.max(y - distance, 0); r < rMax; r++) {
yOff = Math.abs(r - y);
// Work out where we should stop looping for this row
cMax = Math.min(x + distance - yOff + 1, cols);
// Start at the first column with a permissible move
for (c = Math.max(x - distance + yOff, 0); c < cMax; c++) {
// If it's not the current position, add it to the result
if (x != c || y != r)
ret.push([c, r]);
}
}
return ret;
}
為了給你一個更好的想法,我匯總了一個演示,允許你調整所有不同的變量,例如電路板尺寸,距離等。
工作演示: http : //jsfiddle.net/AndyE/fWDHy/2/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.