2017-03-06 46 views
0

我在找到線上的相鄰點時遇到問題。如何在線/折線c上找到相鄰點#

我有一個折線和一個點。這點始終保持在線上。線總是筆直(不是斜線)。

我想找到以前和以下幾點。 (在圖像上是C和D)。做這個的最好方式是什麼?找到先前的點可能會更好(然後,找到下一個點將是微不足道的)。

我的想法是使用循環和if聲明,但也許存在更好的解決方案?

enter image description here

+0

您正在尋找'最近的鄰居'查詢。 –

+0

「直(不是斜)」是指「正交」(即只有水平還是垂直)?無論如何,使用循環可能是最好的方法。 –

+0

是的,只有正交。我應該使用兩次(對於垂直和水平)'for'用'foreach'循環嗎? – Slawkoo

回答

0

這裏是你是否能滿足您的網格轉換成int值的天真的解決方案。它應該涵蓋線路不像平方螺旋線那樣「增長」的情況。 切換到加倍時,請注意可能的舍入問題。

  var line = new List<Point> 
     { 
      new Point("A", 0, 0), 
      new Point("B", 1, 0), 
      new Point("C", 1, 1), 
      new Point("D", 3, 1), 
      new Point("E", 3, 2), 
      new Point("F", 4, 2) 
     }; 

     var p = new Point("P",2,1); 

     Point first = null; 
     foreach (var point in line) 
     { 
      if (first != null) 
      { 
       if (p.X == first.X && p.X == point.X 
        && (p.Y >= first.Y && p.Y <= point.Y 
         || p.Y <= first.Y && p.Y >= point.Y)) 
       { 
        PrintResult(first, p, point); 
        break; 
       } 

       if (p.Y == first.Y && p.Y == point.Y 
        && (p.X >= first.X && p.X <= point.X 
         || p.X <= first.X && p.X >= point.X)) 
       { 
        PrintResult(first, p, point); 
        break; 
       } 

      } 

      first = point; 
     } 

     Console.ReadKey(); 
    } 

    private static void PrintResult(Point first, Point p, Point second) 
    { 
     Console.WriteLine(first.Name); 
     Console.WriteLine(p.Name); 
     Console.WriteLine(second.Name); 
    }