2009-05-29 69 views
0

假設您在二維平面中有兩個點(a,b)。考慮到這兩點,找到線段上最大點的最佳方法是距離距離它最近的每個點等距離,並且距離最小。線段中的等距點

我使用C#,但任何語言的示例都會有所幫助。

List<'points> FindAllPointsInLine(Point start, Point end, int minDistantApart) 
{ 
// find all points 
} 

回答

3

解釋的問題是:

  • 點之間start
  • 並指向end
  • 什麼是點的最大數量其間間隔均勻,至少是minDistanceApart

然後,這很簡單:startend之間的長度除以minDistanceApart,向下舍入減1(不減1),最終得到的是終點之間的距離數量,而不是結束點之間的距離數量)

實現:

List<Point> FindAllPoints(Point start, Point end, int minDistance) 
{ 
    double dx = end.x - start.x; 
    double dy = end.y - start.y; 

    int numPoints = 
     Math.Floor(Math.Sqrt(dx * dx + dy * dy)/(double) minDistance) - 1; 

    List<Point> result = new List<Point>; 

    double stepx = dx/numPoints; 
    double stepy = dy/numPoints; 
    double px = start.x + stepx; 
    double py = start.y + stepy; 
    for (int ix = 0; ix < numPoints; ix++) 
    { 
     result.Add(new Point(px, py)); 
     px += stepx; 
     py += stepy; 
    } 

    return result; 
} 

如果你希望所有的點,包括起點和終點,那麼你就必須調整的循環,並開始「像素」和「PY」在'而是使用「start.x」和「start.y」。請注意,如果端點的準確性至關重要,您可能希望直接根據比率「ix/numPoints」執行「px」和「py」的計算。

+0

鑑於他的原型,他想要一個點的列表,但我認爲你對如何將它們分開的解釋是正確的。 – 2009-05-29 06:19:35

2

我不確定我是否瞭解您的問題,但您是否嘗試劃分這樣的線段?

前:

A + -------------------- + B

後:

A + - | - - | - | - | - | - | - + B

「雙破折號」是您的最小距離嗎?如果是這樣,那麼將有無限多的點滿足這一點,除非你的最小距離可以精確地分割段的長度。

  1. 找到行的矢量參數方程
  2. 查找點的總數(地板(長度/ minDistance纔會)+ 1)
  3. 環路I從:然而,如下可以得到一個這樣的組0到n,發現每一個點沿着線(如果您的參數方程需要在從0到1,T =((浮點)ⅰ)/ N)

[編輯] 看到jerryjvl的答覆後,我想你想要的代碼是這樣的:(用Java-ish做這個)

List<Point> FindAllPointsInLine(Point start, Point end, float distance) 
{ 
    float length = Math.hypot(start.x - end.x, start.y - end.y); 
    int n = (int)Math.floor(length/distance); 
    List<Point> result = new ArrayList<Point>(n); 

    for (int i=0; i<=n; i++) { // Note that I use <=, not < 
     float t = ((float)i)/n; 
     result.add(interpolate(start, end, t)); 
    } 

    return result; 
} 

Point interpolate(Point a, Point b, float t) 
{ 
    float u = 1-t; 
    float x = a.x*u + b.x*t; 
    float y = a.y*u + b.y*t; 
    return new Point(x,y); 
} 

[警告:代碼沒有經過測試]

+0

謝謝,這就是我所需要的。 – user114116 2009-05-29 16:23:44

0

找到合適的點數。計算X和Y座標的步驟並生成點。像這樣:

lineLength = sqrt(pow(end.X - start.X,2) + pow(end.Y - start.Y, 2)) 
numberOfPoints = floor(lineLength/minDistantApart) 
stepX = (end.X - start.X)/numberOfPoints 
stepY = (end.Y - start.Y)/numberOfPoints 
for (i = 1; i < numberOfPoints; i++) { 
    yield Point(start.X + stepX*i, start.Y + stepY*i) 
} 
+0

打敗我吧;) – jerryjvl 2009-05-29 06:24:43