简体   繁体   English

计算数组中的最大值和最小值

[英]Calculating maximum and minimum values in an array

I have an array of integers and need to find the position in the array of the maximum number along with the minimum. 我有一个整数数组,需要在最大数字的数组中找到最小值的位置。 I have it working but it doesn't seem to be a very good way to do it. 我有它工作但它似乎不是一个非常好的方法来做到这一点。 Can anyone suggest a better way to achieve what I have? 任何人都可以建议一个更好的方法来实现我的目标吗?

Here's my code: 这是我的代码:

int[] usageHours = { 3, 3, 5, 4, 0, 0, 2, 2, 4, 25, 158, 320, 212, 356, 401, 460, 480, 403, 298, 213, 102, 87, 34, 45 };
double myAverage = usageHours.Average();
int runningTotal = 0;
int runningMaxPosition = 0;

for (int i = 0; i < usageHours.Length; i++)
{
    if (usageHours[i] > runningTotal)
    {
        runningMaxPosition = i;
        runningTotal = usageHours[i];
    }
}

txtmax.Text = Convert.ToString(runningMaxPosition)+" With: "+Convert.ToString(runningTotal)+" Users";
txtAv.Text = Convert.ToString(myAverage);

That code is mostly fine. 那段代码很好。 I'd suggest changing the variable names a bit, but that's all. 我建议稍微更改变量名称,但这就是全部。 You can work out the minimum in the same loop. 您可以在同一循环中计算出最小值。 I've changed the "if" conditions very slightly to guarantee that they always pick out at least one element (even if all the values are, say, int.MinValue ). 我已经非常轻微地改变了“if”条件,以保证它们总是挑出至少一个元素(即使所有的值都是int.MinValue )。 There are other ways of approaching this, but this is one example. 还有其他方法可以解决这个问题,但这只是一个例子。 If you have an empty array, you'll end up with max=min=0, and both indexes=-1. 如果你有一个空数组,你最终会得到max = min = 0,并且两个索引都是-1。

int currentMax = 0;
int currentMaxIndex = -1;
int currentMin = 0;
int currentMinIndex = -1;

for (int i = 0; i < usageHours.Length; i++)
{
    if (currentMaxIndex == -1 || usageHours[i] > currentMax)
    {
        currentMaxIndex = i;
        currentMax = usageHours[i];
    }
    if (currentMinIndex == -1 || usageHours[i] < currentMin)
    {
        currentMinIndex = i;
        currentMin = usageHours[i];
    }
}

Here's an alternative using nullable value types to represent "there were no values" answers: 这是使用可空值类型来表示“没有值”答案的替代方法:

int currentMax? = null;
int currentMaxIndex? = null;
int currentMin? = null;
int currentMinIndex? = null;

for (int i = 0; i < usageHours.Length; i++)
{
    if (currentMax == null || usageHours[i] > currentMax.Value)
    {
        currentMax = i;
        currentMax = usageHours[i];
    }
    if (currentMin == null || usageHours[i] < currentMin.Value)
    {
        currentMinIndex = i;
        currentMin = usageHours[i];
    }
}

Don't worry if you haven't come across nullable value types yet though... 如果您还没有遇到可以为空的值类型,请不要担心...

The code looks OK for finding the max value. 代码看起来可以找到最大值。 If you are using C# 3 or later you could use the LINQ extension methods (there are Min , Max and Average methods, and on List there is also a FindIndex method, amongst others), but I get the impression that you are learning programming, and then it is sometimes a good idea to implement stuff that may be built into the framework, just for the learning value. 如果你使用的是C#3或更高版本,你可以使用LINQ扩展方法(有MinMaxAverage方法,在List上也有FindIndex方法,等等),但我得到你正在学习编程的印象,然后有时候一个好主意是实现可以构建到框架中的东西,只是为了学习价值。

I just wanted to provide one-liner solution for the question (for completeness). 我只是想为问题提供单线解决方案(完整性)。 In the OP's original question he only asks for index of the maximum and index of the minimum. 在OP的原始问题中,他只询问最大值的索引和最小值的索引。

Let's stick to this question. 让我们坚持这个问题。 This is the most interesting question because to find maximum value we can simply use Enumerable.Max LINQ method. 这是最有趣的问题,因为要找到最大值,我们可以简单地使用Enumerable.Max LINQ方法。 The same goes for Min and Average. Min和Average也是如此。

Let's only provide index of the max, index of min can be retrieved with similar code. 我们只提供max的索引,min的索引可以用类似的代码检索。

int indexOfMax = Enumerable.Range(0, usageHours.Length).Aggregate(
    (indexOfMax, i) => (usageHours[i] > usageHours[indexOfMax] ? i : indexOfMax)
);

Delegate inside of Aggregate's brackets is executed for each index of array. 对每个数组索引执行Aggregate括号内的委托。 It gets as parameters "index of maximum value so far found", and current index. 它获取参数“迄今为止找到的最大值索引”和当前索引。 It returns "index of maximum value so far found". 它返回“到目前为止找到的最大值索引”。 Obviously in each iteration "index of maximum value so far found" will only change to current index if corresponding element of array is greater than previous maximum. 显然,在每次迭代中,“当前找到的最大值索引”将仅在数组的对应元素大于先前最大值时才变为当前索引。

scratch the linq code, it didnt work the way you wanted 抓住linq代码,它没有按你想要的方式工作

you could make your code a little bit more concise 你可以让你的代码更简洁一些

for (int i = 0; i < usageHours.Length; i++)
{
    if (usageHours[i] > usageHours[runningMaxPosition])
        runningMaxPosition = i;
}

all it does differently is leavs out the temporary runningTotal variable. 所有它做的不同就是抛出临时的runningTotal变量。

How about this: 这个怎么样:

double average = usageHours.Average();
int maxPosition = Enumerable.Range(0, usageHours.Length).Max(i => usageHours[i]);
int minPosition = Enumerable.Range(0, usageHours.Length).Min(i => usageHours[i]);

Your code isn't bad, but it won't work if all the values are less than zero. 您的代码并不错,但如果所有值都小于零,它将无法运行。

Try this: 尝试这个:

int getArrayMaxPosition (double[] theArray) 
{    
    double maxVal = theArray[0];
    int ret = 0;
    int currentIndex = 0;

    foreach (double aValue in theArray) 
    {
        if (aValue > maxVal)
        {
             ret = currentIndex;
             maxVal = avalue;
        }
        currentIndex++;
    }

    return ret;
 }

As was mentioned on the comment's to Jon's answer, Jon's solution really is the best, most direct, quickest way of doing it. 正如评论中提到Jon的回答一样,Jon的解决方案确实是最好,最直接,最快捷的解决方案。

If, however, you did want to use Igor's solution, here's the rest of it (to get the actual positions as well as the values): 但是,如果您确实想要使用Igor的解决方案,那么其余部分(获取实际位置以及值):

int maxValue = Enumerable.Range(0, usageHours.Length).Max(i => usageHours[i]);
int maxPosition = Array.FindIndex(usageHours, i => i == maxValue);
int minValue = Enumerable.Range(0, usageHours.Length).Min(i => usageHours[i]);
int minPosition = Array.FindIndex(usageHours, i => i == minValue);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM