Click here to Skip to main content
15,899,007 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi
can any one tell, the best way to find a value from an array which is repeated most times

ex
string[] array = new string[] {"1","2","2","3","3","4","2","3","4","4","2","2",};

Expect Ans: 2
Posted
Updated 7-Jul-12 0:04am
v2

"Best" in what sense?
There are a huge variety of ways to do this, a few of which are:
1) A foreach loop, counting occurrences into a separate array or Dictionary. Then sort the instances my count, and take the top value.
2) A Linq Query to do the same.
3) Sort the original array, then loop though, counting occurrences and picking the largest as you go.

Which way would I do it? Depends on what the data to check was, and how many of them there were.

"Best" is a subjective word - it can mean "fastest", "smallest", "clearest", "most understandable" or even "least understandable so no-one else will touch it".
 
Share this answer
 
Comments
OriginalGriff 7-Jul-12 6:24am    
We do not do your homework: it is set for a reason. It is there so that you think about what you have been told, and try to understand it. It is also there so that your tutor can identify areas where you are weak, and focus more attention on remedial action.

Try it yourself, you may find it is not as difficult as you think!
Mohd Imran Saifi 7-Jul-12 6:28am    
i also agree with Orginal giff.
use the Third type . just sorting the array, then check redundency of every value. pick the largest redundant value.
This is the Best logic Which OriginalGriff is metion. Write the code by yourself.
Well this is maybe a not the most elegant solution but it does the job:

C#
public string GetMaxElementCount(string[] array)
{
    List<string> list = new List<string>(array);
    IEnumerable<IGrouping<string, string>> g = list.GroupBy(i => i);

    int countMax = 0;
    string keyMax = string.Empty;

    foreach (IGrouping<string, string> grp in g)
    {
        int count = grp.Count();
        if (countMax < count)
        {
            countMax = count;
            keyMax = grp.Key;
        }

    }

    return keyMax;
}




Cheers
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900