Search code examples
c#listsortinglanguage-agnosticicomparer

Implementing a sorting mechanism with 3 or more parameters


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.


Solution

  • 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.