Today I present to you a function that takes in a list of integer values and a matching list of custom typed objects and returns the object that corresponds to the largest numerical value from the source list, or a default value when all integers are found to be equal.

    public static T selectMax<T>(int[] selectors, T[] values, T defaultValue)
    {
        int imax = 0; // first element = 1, or i+1

        for (int i = 1; i < selectors.Length; i++)
        {
            if (imax == 0)
            {
                if (selectors[i] == selectors[i - 1])
                    continue;

                imax = i;
            }

            if (selectors[i] > selectors[imax - 1])
            {
                imax = i + 1;
            }
        }

        return imax == 0 ? defaultValue : values[imax - 1];
    }

 

Usage

Say you are trying to read the suit value of a card where each suit has own color as follows:

  • Red – Hearts
  • Green – Clubs
  • Blue – Diamonds
  • Black – Spades

Simply by analyzing the RGB histogram of a source image (or region that represents said suit) you can then determine suit value via:

 
string suit = selectMax<string>(
                   new int[] { r, g, b },
                   new string[] { "Heart", "Club", "Diamond" }, "Spade");