Tengo esta matriz. Escribí una función MostFreq que toma una matriz de enteros y devuelve 2 valores: el número más frecuente en la matriz y su frecuencia comprueba este código. ¿Qué crees? ¿Hay una mejor manera de hacerlo?El número más frecuente en una matriz
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);
}
=====
en el MyMath clase
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);
}
¿Por qué se ha declinado y se ha calificado ofensivo? – FlySwat
@Brandon ¿Qué versión de C# estás usando? –
Acabo de editar las etiquetas para que la gente sepa a qué versión apuntar. –