HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Most common occurrence of an int in an array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arrayoccurrenceintcommonmost

Problem

I am prepping for a junior level interview in C#. I am hoping I can get some feedback on how to improve my code to print the most common occurrence of an int in an array.

using System;
using System.Collections;

namespace FrequentInt
{
    class MainClass
    {

        static void CommomOcurrence (int [] array, Hashtable hs)
        {
            int mostCommom = array[0];
            int occurences = 0;
            foreach (int num in array) 
            {
                if (!hs.ContainsKey (num)) {
                    hs.Add (num, 1);
                } 
                else 
                {
                    int tempOccurences = (int)hs [num];
                    tempOccurences++;
                    hs.Remove (num);
                    hs.Add (num, tempOccurences);

                    if (occurences < tempOccurences)
                    {
                        occurences = tempOccurences;
                        mostCommom = num;
                    }
                }
            }
            foreach(DictionaryEntry entry in hs)
            {
                Console.WriteLine("{0}, {1}", entry.Key, entry.Value);
            }
            Console.WriteLine ("The commmon numer is " + mostCommom + " And it appears " + occurences + " times");
        }

        public static void Main (string[] args)
        {

            int[] array = new int[20]{ 3,6,8,5,3,5,7,6,4,3,2,3,5,7,6,4,3,4,5,7}; 
            Hashtable hs = new Hashtable ();
            CommomOcurrence (array, hs);

        }
    }
}

Solution

Whenever you're dealing with collections in C#, there's often a simple Linq solution.

Instead of using a Hashtable or Dictionary to group together and count each occurrence, use the .GroupBy method on the integers. This makes each integer a key with a list of values for each occurrence.

Then all you need to do to find the largest is to order by occurrence and take the first result. Using Linq's .OrderByDescending and .First methods do this for you.

static void CommonOccurrence(int[] numbers)
{
    var groups = numbers.GroupBy(x => x);
    var largest = groups.OrderByDescending(x => x.Count()).First();
    Console.WriteLine("The most common number is {0} and it appears {1} times", largest.Key, largest.Count());
}


If you wanted to take the same approach without relying on Linq to group and sort for you, you can make separate methods for each action you need to perform, as per the Single Responsibility Principle:

static void CommonOccurrence(int[] numbers)
{
    var dictionary = GroupByOccurrence(numbers);
    var mostCommonNumber = KeyOfLargestValue(dictionary);
    var occurrences = dictionary[mostCommonNumber];
    Console.WriteLine("The most common number is {0} and it appears {1} times", mostCommonNumber, occurrences);
}

static Dictionary GroupByOccurrence(int[] numbers)
{
    var result = new Dictionary();
    foreach (int i in numbers)
    {
        if (!result.ContainsKey(i))
        {
            result[i] = 0;
        }
        result[i]++;
    }
    return result;
}

static int KeyOfLargestValue(Dictionary dictionary)
{
    int result = dictionary.Keys.First();
    foreach (var entry in dictionary)
    {
        if (entry.Value > dictionary[result])
        {
            result = entry.Key;
        }
    }
    return result;
}

Code Snippets

static void CommonOccurrence(int[] numbers)
{
    var groups = numbers.GroupBy(x => x);
    var largest = groups.OrderByDescending(x => x.Count()).First();
    Console.WriteLine("The most common number is {0} and it appears {1} times", largest.Key, largest.Count());
}
static void CommonOccurrence(int[] numbers)
{
    var dictionary = GroupByOccurrence(numbers);
    var mostCommonNumber = KeyOfLargestValue(dictionary);
    var occurrences = dictionary[mostCommonNumber];
    Console.WriteLine("The most common number is {0} and it appears {1} times", mostCommonNumber, occurrences);
}

static Dictionary<int, int> GroupByOccurrence(int[] numbers)
{
    var result = new Dictionary<int, int>();
    foreach (int i in numbers)
    {
        if (!result.ContainsKey(i))
        {
            result[i] = 0;
        }
        result[i]++;
    }
    return result;
}

static int KeyOfLargestValue(Dictionary<int, int> dictionary)
{
    int result = dictionary.Keys.First();
    foreach (var entry in dictionary)
    {
        if (entry.Value > dictionary[result])
        {
            result = entry.Key;
        }
    }
    return result;
}

Context

StackExchange Code Review Q#100349, answer score: 8

Revisions (0)

No revisions yet.