2

C# でジェネリック バイナリ ツリーをコーディングしています。

アプリケーションの一部で、距離の順に並べ替える必要があります。

AからCへ、BからCへ。

このようなもの:

if ((A->C) == (B->C))  
    return 0;
else if((A->C) < (B->C))
    return -1;
else
    return 1;

しかし、問題は、2 つのオブジェクト間でしか比較できないことです...そして、ある種のコンパレーターが必要です。

「開始と終了の間の距離」のようなクラスを作成することは正しい解決策ですか? ゴミが多すぎると思います。

解決策はありますか?ありがとう ;-)

編集:

public AvlNode<T> _left, _right;
public Stack<T> _obj;

(...)

public AvlNode<T> Insert(T obj, IComparer<T> iComparer)
    {
        if (iComparer.Compare(obj, _obj.Peek()) > 0)
        {
            _right = (_right != null) ? _right.Insert(obj, iComparer) : new AvlNode<T>(obj);
            return Balance();
        }
        else if (iComparer.Compare(obj, _obj.Peek()) < 0)
        {
            _left = (_left != null) ? _left.Insert(obj, iComparer) : new AvlNode<T>(obj);
            return Balance();
        }
        else
        {
            _obj.Push(obj);  // distance already exists but object may be different, that's why I use a stack...
            return this;
        }
    }

動作する IComparer がありません...

編集:

問題が解決し、IComparer が動作するようになりました!

public class ObjectDistanceComparer : IComparer<EraObject>
{
    Vector3 _position;


    public ObjectDistanceComparer(Vector3 position)
    {
        _position = position;
    }

    int IComparer<EraObject>.Compare(EraObject obj1, EraObject obj2)
    {
        float d1 = (_position - obj1._position).LengthSquared();
        float d2 = (_position - obj2._position).LengthSquared();
        return (d1 == d2)? 0 : (d1 < d2)? -1 : 1;
    }
}

ありがとう ;-)

4

2 に答える 2

3

Node クラスに追加のプロパティを追加できます。

public class Node : IComparable
{
   Node Parent{get;set;}
   Node LChild {get;set;}
   Node RChild {get;set;}
   Node C {get;set;}

   public int CompareTo(object o)
   {
      // Now you passed C in your object, do stuff ...
   }
}
于 2012-08-19T00:48:04.730 に答える
1
public class Distance
{
int Source {get;set;}
int Destination{get;set;}
int Value{ 
          get{ return Math.Abs(Destination - Source);}
         }
}
于 2012-08-19T00:56:56.120 に答える