Determine if number n contains the same number 3 times and if yes, print it [closed]

Posted on

Problem

My problem is to Determine if number n contains the same number 3 times and if yes, print it.

I have presented number in array form. for this a, this algorithm prints 2 on console.

My algorithm looks like this:

// a = 542383272
int[] a = { 5, 4, 2, 3, 8, 3, 2, 7, 2 };

for (int i = 0; i < a.Length - 1; i++)
{
    int count = 0;
    for (int j = i + 1; j < a.Length; j++)
    {
        if (a[i] == a[j])
        {
           count++;
           if (count == 2)
              Console.WriteLine(a[i]);
        }
    }
}

My question is How can I make this algorithm faster and more efficient?

Solution

You are only dealing with ten possible digit-outcomes. At the moment, your algorithm is in the order of n-squared, because for each digit in the original number you iterate through the array again (albeit slightly truncated).

You also don’t address what happens if the digit occurs more than three times. I assume that this is ignored deliberately.

What you can do is run through the number once, and adjust the count of a single array. Then run through this array to identify those that have a count of 3. I am not a C# coder, so that following is pseudo code.

Split yourNumber into an array of digits (yourNumberArray) // could be a string array
Create an empty array of 10 elements (countArray) // indexes will be 0-9, which neatly matches what you want to capture - this is not a coincidence.
Traverse yourNumberArray, for each digit increment the corresponding index in countArray
After counting, traverse countArray and output those digits where the count = 3 // or whatever value you want

This will be O(n+10). Not a big deal if you are only talking a few digits, but if you are dealing with a few million digits, a big difference!

You can group the elements based on the number. Then get the required count.

bool HasRequiredCount(int[] elements, int count)
{
    bool result = false;
    var groupByCount = elements.ToList().GroupBy(i => i);
    foreach(var group in groupByCount)
    {
        int grpCount = group.Count();
        if (grpCount == count)
        {
            System.Diagnostics.Debug.WriteLine("YES Matched : {0} {1}", group.Key, grpCount);
            result = true;
            break;
        }
        else
        {
            System.Diagnostics.Debug.WriteLine("Not Matched: {0} {1}", group.Key, grpCount);
        }
    }

    return result;
}

Leave a Reply

Your email address will not be published. Required fields are marked *