The Most frequent Number in an array

后端 未结 9 1607
粉色の甜心
粉色の甜心 2021-01-17 14:14

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

9条回答
  •  借酒劲吻你
    2021-01-17 15:05

    Here's an example how you could do it without LINQ and no dictionaries and lists, just two simple nested loops:

    public class MostFrequentNumber
    {
        public static void Main()
        {
            int[] numbers = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
    
            int counter = 0;
            int longestOccurance = 0;
            int mostFrequentNumber = 0;
    
            for (int i = 0; i < numbers.Length; i++)
            {
                counter = 0;
    
                for (int j = 0; j < numbers.Length; j++)
                {
                    if (numbers[j] == numbers[i])
                    {
                        counter++;
                    }
                }
    
                if (counter > longestOccurance)
                {
                    longestOccurance = counter;
                    mostFrequentNumber = numbers[i];
                }
            }
    
            Console.WriteLine(mostFrequentNumber);
            //Console.WriteLine($"occured {longestOccurance} times");
        }
    }
    

    You get the value of the most frequently occurring number, and (commented) you could get also the numbers of the occurrences. I know I have an "using Linq;", that's just to convert the initial input string to an int array and to spare a couple of lines and a parsing loop. Algorithm is fine even without it, if you fill the array the "long" way...

提交回复
热议问题