Domanda

I'm trying to implement icomparer or some other form of list sorting comparison to sort a list of vector3s.

The vector3s are being compared to a reference vector3 and then being sorted based on their distances.

I can't figured out how to get IComparer to allow 3 parameters, or how to sort my list with a third parameter.

Basically, this is how I'm trying to sort it.

Class VectorSorter : IComparer<Vector3>
{
    public int Compare(Vector3 base, Vector3 spot1, Vector3 spot2)
    {
        return (base-spot1).magnitude.CompareTo((base-spot2).magnitude);
    }
}

If anyone knows how to implement IComparer with 3 values or where I should look for sorting a list with 3 values, I'd appreciate it.

È stato utile?

Soluzione

First, I don't actually know what language you are posting in, I can't identify it. But, this answer is fairly language-agnostic, so please translate back to your preferred language. I have guessed at the syntax below.

You need to find a way to parameterize and calculate your search metric such that any two object a and b can be distinctly ordered based on a scalar value without additional information during the sort.

For example, if base is constant for a given sort operation:

Class VectorSorter : IComparer<Vector3> {

    private Vector3 base;

    public VectorSorter (Vector3 base) { 
       this.base = base; 
    }

    public int compare (Vector3 spot1, Vector3 spot2) {
       return (base-spot1).magnitude.CompareTo((base-spot2).magnitude);
    }

}

Then you pass new VectorSorter(theBaseToUseWhenSorting) as the comparator to your sort function.

If base isn't constant then you will need to find another way to express your data set, in a way that has a distinct natural ordering; perhaps create some object that holds calculation results then sort a list of those objects based on a scalar result of the calculation, etc. I can't really give you any more specific advice (or even a good example) there without knowing more about how base correlates with spot1 and spot2 during the sort operation.

Altri suggerimenti

If it's C# you can take advantage of LINQ.

return from v in list
       select v
       orderby (v - base).magnitude;

This is neither possible with IComparer<T>, nor is it conventional.

An ordering - which is indicated by the result of Compare - is done against two values. This is codified into the interface and there is no provision for three values.

A sort algorithm (or any code that accepts an IComparer) will apply the ordering function multiple times over two values as required.


I suspect that you really wish to "have access to" a common base vector (avoid keywords, btw) in the Compare function; the easiest way to do this is to supply it as a constructor argument and store/access it as a member field of the Comparer object.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top