在阵列最频繁的号码 [英] The Most frequent Number in an array
本文介绍了在阵列最频繁的号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的阵列我写了一个函数MostFreq这需要一个整数数组,并返回2值:更频繁一些阵列中,它的频率检查该$ C $词又写道你有什么感想?有没有更好的办法做到这一点?
静态无效的主要()
{
INT [] M = {4,5,6,4,4,3,5,3};
INT X;
INT F = MyMath.MostFreq(男,出X);
console.WriteLine(最频繁项= {0}频率= {1},X,F);
}
=====
在类MYMATH
公共静态INT MostFreq(INT [] _M,OUT INT X)
{
//首先,我要在升序排序数组
INT Max_Freq,No_Freq,I,K;
的Array.Sort(_M);
K = _M [0];
Max_Freq = 0; I = 0; X = 0;
而(I< _M.Length)
{
// No_Freq =当前数量的频率
No_Freq = 0;
// X这里是它是在数组中出现频繁的数量
而(K == _M [I])
{
No_Freq ++;
我++;
如果(我== _M.Length)
打破;
}
如果(No_Freq> Max_Freq)
{
//所以它将被打印在同一
Max_Freq = No_Freq;
X = K表;
}
如果(ⅰ&其中; _M.Length数)k = _M [I];
}
返程(Max_Freq);
}
解决方案
LINQ起来。我知道这是在VB,但你应该能够将其转换为C#:
暗淡I =从数字的整数_
组号码通过数字到集团_
总结FEQ在集团进入计数()_
选择新用{.Number =号码,.Count之间=计数}
编辑:现在,在C#中太:
变种我从并购数量=
一组数字由数字到分组
选择新的{数= grouped.Key,频率= grouped.Count()};
I have this Array i wrote a function MostFreq that takes an array of integers and return 2 values : the more frequent number in the array and its frequency check this code i worte what do you think ? is there a better way to do it?
static void Main()
{
int [] M={4,5,6,4,4,3,5,3};
int x;
int f=MyMath.MostFreq(M,out x );
console.WriteLine("the most Frequent Item = {0} with frequency = {1}",x,f);
}
=====
in the class Mymath
public static int MostFreq(int[] _M, out int x)
{
//First I need to sort the array in ascending order
int Max_Freq, No_Freq, i, k;
Array.Sort(_M);
k = _M[0];
Max_Freq = 0; i = 0; x = 0;
while (i < _M.Length)
{
//No_Freq= the frequency of the current number
No_Freq = 0;
//X here is the number which is appear in the array Frequently
while (k == _M[i])
{
No_Freq++;
i++;
if (i == _M.Length)
break;
}
if (No_Freq > Max_Freq)
{
//so it will be printed the same
Max_Freq = No_Freq;
x = k;
}
if (i < _M.Length) k = _M[i];
}
return (Max_Freq);
}
解决方案
LINQ it up. I know this is in VB but you should be able to convert it to C#:
Dim i = From Numbers In ints _
Group Numbers By Numbers Into Group _
Aggregate feq In Group Into Count() _
Select New With {.Number = Numbers, .Count = Count}
EDIT: Now in C# too:
var i = from numbers in M
group numbers by numbers into grouped
select new { Number = grouped.Key, Freq = grouped.Count()};
这篇关于在阵列最频繁的号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文