2016-10-27 6 views
0

こんにちはこれは私の問題点です。私は点P(x、y)の配列を持っています。そして、これらの点をポリゴンの重心に対して最も遠くから最も近い点からソートする必要があります。私は何をしましたか(私はこれが悪い解決策であることを知っています)。あなたの答えのための配列をソートする最速の方法C#

List<C2DPoint> OrderedGripperPoints = new List<C2DPoint> { }; 

while(myGripperPoints.Count!=0) 
{ 
    double dist=-1; 
    int index=-1; 
    for(int k=0;k<myGripperPoints.Count;k++) 
    { 
     if(myGripperPoints[k].Distance(WorkScrap.GetCentroid())>=dist) 
     { 
      index = k; 
      dist = myGripperPoints[k].Distance(WorkScrap.GetCentroid()); 
     } 
    } 

    OrderedGripperPoints.Add(myGripperPoints[index]); 
    myGripperPoints.RemoveAt(index); 
} 

おかげで...

+0

を降順であるList<KeyValuePair<Point,int>>、だろうと降順での距離によって行われC2DPoint' 'の作成時に距離を事前計算することが可能ですか? –

+0

@NiyokoYuliawan yeasそれは –

+0

ですArray.Sortも使用できます –

答えて

4

ポイントを注文するのLINQを使用してください。

+0

答えが –

+1

ありがとう –

1
using System.Linq; 

var sortedList = myGripperPoints.OrderBy(p => p.Distance(WorkScrap.GetCentroid())).ToList(); 

は、以下のコードを検討:

ポイントクラス(想定クラス定義)

class Point 
{ 
    public int X { get; set;} 

    public int Y { get; set;} 
} 

ポイントEqualityComparer

class PointEqualityComparer : IEqualityComparer<Point> 
{ 
    public bool Equals(Point p1, Point p2) { return p1.X == p2.X && p1.Y == p2.Y; } 

    public int GetHashCode(Point p) { return p.X.GetHashCode() *31 + p.Y.GetHashCode()*23; } 
} 

(整数を想定)の値としてキーとの距離などの点で辞書を作成します。

Dictionary<Point,int> pointDictionary = 
new Dictionary<Point, int>(new PointEqualityComparer()); 

次のようにポイントを追加します。

Point p = new Point {X = <value>, Y = <value>}; 
pointDictionary.Add(p,p.Distance(WorkScrap.GetCentroid())); 

注文を距離によって次のように:

pointDictionary.OrderByDescending(x => x.Value).ToList(); 
  1. 注文が期待
  2. 結果は、要素が順番
+0

投稿された質問に基づいて、これは「OrderByDescending」にする必要があります。このソリューションは、さらに多くの詳細な穀粒制御を提供しますプロパティはDictionary の一部で、Orderedコレクションで使用することができます –

+0

@AntonínLejsekは指摘してくれてありがとうございます。ユニークなハッシュを持つことの保証はまだそこにはないかもしれませんが、衝突を減らします –

関連する問題