简体   繁体   English

在数组中查找最高和最低值并删除它们以计算平均 C#

[英]Finding Highest and Lowest value in Array and removing them to compute an average C#

I am trying to write code that finds the lowest and highest values stored in an array and then removes them from the array to compute an average.我正在尝试编写代码来查找存储在数组中的最低和最高值,然后将它们从数组中删除以计算平均值。

Currently I have written code to produce the average of all numbers in the array but I need to change that once I figure out how to remove Highest and lowest value.目前我已经编写了代码来生成数组中所有数字的平均值,但是一旦我弄清楚如何删除最高和最低值,我就需要更改它。

Code I have:我有代码:

private void HighAndLow()
{
    try
    {
        int[] HighAndLowGrade;
        int[] highest = HighAndLowGrade.Max();
        int lowest = HighAndLowGrade.Min();
    }
    catch
    {
        MessageBox.Show("HighAndLow Method failed");
    }
}
        
//find average without highest and lowest values
private void ComputeMean()
{
    double total = 0;
    for (int index = 2; index < 9; index ++)
    {
        total += double.Parse(lineContent[index]);
    }
    averageTestScore = total / 7;
 }

This only requires one iteration through the collection:这只需要对集合进行一次迭代:

public double ComputeAdjustedMean(IEnumerable<int> items)
{
    int total = 0;
    int count = 0;
    int min = int.MaxValue;
    int max = int.MinValue;

    foreach(int item in items)
    {
        count++;
        total += item;
        if (item < min) min = item;
        if (item > max) max = item;
    }

    if (count <= 2) // not enough items
    {
       // do something here
    }
    return (total - (min + max)) / (double)(count - 2);
}

    

This should work from what I have tested so far.这应该从我到目前为止测试过的内容中起作用。

int[] numberArray = new int[] {1,2,5,9,5,2};
double answer = 0;

var ignoreList = new List<decimal>() {
    numberArray.Max(),
    numberArray.Min()
};

var cleanList = numberArray.Where(x => !ignoreList.Contains(x));

answer = cleanList.Any() ? cleanList.Average() : 0;

Try this using bubble sorting algorithm-使用冒泡排序算法试试这个 -

 static void Main(string[] args)
    {
        int[] array = { 12, 6, 34, 23, 89 };
        int temp;


            for (int i = 0; i <= array.Length - 2; i++)
            {
                if (array[i] > array[i + 1])
                {
                    temp = array[i];
                    array[i] = array[i + 1];
                    array[i + 1] = temp;
                }
            }
        array = array.Skip(1).SkipLast(1).ToArray();
        Console.WriteLine((array.Sum()) / (array.Length));
        Console.Read();
    }

If you have an array of values then you can do this neat LINQ query:如果您有一组values那么您可以执行以下简洁的 LINQ 查询:

var average_skip_min_and_max =
    values
        .OrderBy(x => x)
        .Skip(1)
        .Take(values.Length - 2)
        .Average();

I really don't get people when they encounter this kind of questions, they became insanely eager to provide a direct answer .当人们遇到这种问题时,我真的不明白,他们变得非常渴望提供直接的答案 This question is obviously a homework assignment.这个问题显然是一个家庭作业。 I'm not saying we don't help OPs but we need to lead them to solutions.我并不是说我们不帮助 OP,但我们需要引导他们找到解决方案。

Dear OP,亲爱的 OP,

Do not use the LINQ, yet .不要使用LINQ, I think your instructor is meaning you to learn the sorting algorithms and memory operations.我认为你的导师是想让你学习排序算法和内存操作。 Do some research about them, say, Buble Sort , to sort the array you have.对它们进行一些研究,例如Buble Sort ,以对您拥有的数组进行排序。 Then it'll be in front of you how to implement and use.那么如何实现和使用就摆在你面前了。 After then, you should use the framework provided methods like LINQ's Min() / Max() extension methods.之后,您应该使用框架提供的方法,例如 LINQ 的Min() / Max()扩展方法。

The approach to your problem is could be like this:解决您的问题的方法可能是这样的:

  1. Sort the array ascending.对数组进行升序排序。
  2. Get the first element which is now the minimum valued element.获取现在是最小值元素的第一个元素。
  3. Reallocate a new array but 1 element shorter重新分配一个新数组,但缩短 1 个元素
  4. Copy your entire array with the current ordered state to newly allocated array but skip the first element when copying, start with next element.将具有当前有序状态的整个数组复制到新分配的数组,但在复制时跳过第一个元素,从下一个元素开始。
  5. Get the minimum again, but this time search in the newly allocated array and check with the previous minimum再次获取最小值,但这次在新分配的数组中搜索并检查之前的最小值
    • If they are equal go the 3rd operation, if you need to eliminate the repeating minimums ( [1, 1, 2, 3 ...] ), which I think you need to.如果它们相等,则进行第三次操作,如果您需要消除重复最小值( [1, 1, 2, 3 ...] ),我认为您需要这样做。
    • If they are not equal, then it means you've found the minimum element of your array and removed all occurences如果它们不相等,则意味着您已找到数组的最小元素并删除了所有出现的元素

Now if you repeat the approach to finding the maximum valued element you are done with the elimination process.现在,如果您重复查找最大值元素的方法,则消除过程就完成了。

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

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