I've written a little method that returns the index of the maximum of 3 numbers (0, 1 or 2):

``````public static int Max3Index(float val1, float val2, float val3)
{
int index = val1 > val2 ? 0 : 1;

if (index == 0)
{
index = val1 > val3 ? 0 : 2;
}
else
{
index = val2 > val3 ? 1 : 2;
}

return index;
}``````

This works until 2 or more numbers are equal. What the heck should I do when this condition occurs?

2
Contributors
1
2
Views
8 Years
Discussion Span
Last Post by apegram

That is subjective. In a business application, that would have to determined as part of the requirements. First, you would want to determine if two (or more) elements having the same value is acceptable or an error condition. If it is permissible, then you or the customer must determine which index to return. There's no hard and fast rule, but it is not uncommon to return the first of the matching elements in the case of a tie. If that is something you wanted to do, you could write the method like this.

``````public static int Max3Index(float val1, float val2, float val3)
{
if (val1 >= val2 && val1 >= val3)
return 0;
else if (val2 >= val3)
return 1;
else
return 2;
}``````

You could also write your method to support an array of values rather than 3 individual parameters.

``````public static int MaxIndex(float[] values)
{
float maxValue = float.MinValue;
int index = 0;

for (int i = 0; i < values.Length; i++)
{
if (values[i] > maxValue)
{
maxValue = values[i];
index = i;
}
}

return index;
}``````

Another method

``````public static int MaxIndex(float[] values)
{
float maxValue = values.Max();
int index = values.ToList().IndexOf(maxValue);

return index;
}``````

You could even let LINQ do it for you.

``````public static int MaxIndex(float[] values)
{
int index = (from item in values.Select((f, idx) => new { Value = f, Index = idx })
orderby item.Value descending
select item.Index).FirstOrDefault();

return index;
}``````

If you're worried about performance, the first array method I provided would be best, as it will only need to iterate over the array once.

Edited by apegram: n/a