如何计算数组中有多少个? [英] How to count how many maximum are in an array ?

查看:88
本文介绍了如何计算数组中有多少个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个功能,我希望你能帮我找到我想要打印的最大值是多少:

i have this function, and i want you're help to find if there is more than one maximum i want to print:

No unique max.





我的尝试:





What I have tried:

int find_max(int b[N][N])
{
   nt max = b[0][0];
   int x,y;
   int counter=0;
   int a=0,v=0,c=0;
   for (x = 0; x < N; x++)
   {
       for (y = 0; y < N; y++)
       {
           if (max < b[x][y])
           {
               max = b[x][y];
                a=x;
                v=y;
           }
       }
   }

    c=((a*10)+v);
    for (x = 0; x < N; x++)
   {
       for (y = 0; y < N; y++)
       {
           if((b[x][y]) == max);
           counter++;
       }
   }
 if(counter>1)
   printf("no uniqe max");
else
   return c;
}

推荐答案

首先,只有一个最大值。更确切地说,可以具有无限数量的点的任意函数,其值具有定义的顺序关系,可以具有或不具有最大值,但是对于具有有限数量的元素的数组,存在一个最大值。什么是多重?实现元素最大值的数组索引集。如何计算它们?



一个显而易见的解决方案是:在第一个循环(在你的情况下,这是一个嵌套循环)中,你找到了最大值本身。完成后,在类似的嵌套循环中再次遍历所有值,并计算达到最大值的个案数量(x,y对索引的组合)。



我希望现有算法中的错误非常明显。让我们看看:当您为 max 分配新值时,您总是递增计数器。但是,在一般情况下, max 的值不等于最大值,所以你增加计数器的次数是你应该的。



正如我所看到的,你引用了足够的知识来使用我的建议来修复你的代码。请这样做。



-SA
First of all, there is exactly one maximum. More exactly, an arbitrary functions which may have infinite number of points, which values have relationship of order defined, may or may not have a maximum, but for the arrays, which are have finite number of elements, there is one maximum. What is multiple? The set of array indices on which the maximum value of element is achieved. How to count them?

One obvious solution is: in first loop (in your case, this is a nested loop) you find the maximum value itself. When it is done, traverse all the values again in the similar nested loop, and count the number of cases (combination of x, y pairs of indices) where the maximum is achieved.

I hope the bug in your existing algorithm is quite obvious. Let's see: when you assign new value to max, you always increment the counter. But, in general case, the value of max is not equal to the maximum value yet, so you increment the counter more times that you really should.

As I can see, you have quote enough knowledge to fix your code using my suggestion. Please do it.

—SA


这篇关于如何计算数组中有多少个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆