Live with Dot Net Just another Programming weblog

Get Maximum duplicated value in a array list

Posted on July 19, 2010

The below code give you the Maximum Value with have duplicated in the provided Array of Integer.
I have used Hashtable and try to Sort the Hashtable by Value instead of Key and get the respective Key of the maximum value data.


public class Testing {
//Type 1
public int GetMaxDuplicateValueType1(int[] ValueList)
{
Hashtable slData = new Hashtable();

int maxDuplicateCount=0;
int maxDuplicate = 0;

foreach(int key in ValueList)
{
if (slData.Contains(key))
{
slData[key] = (int)slData[key] + 1;
if ((int)slData[key] > maxDuplicateCount)
{
maxDuplicate = key;
maxDuplicateCount = (int)slData[key];
}
}
else
slData.Add(key, 0);
}
return maxDuplicate;
}

//Type 2
public int GetMaxDuplicateValueType2(int[] ValueList)
{
Hashtable slData = new Hashtable();

foreach(int value in ValueList)
{
if (slData.Contains(value))
slData[value] = (int)slData[value] + 1;
else
slData.Add(value, 0);
}

ArrayList aList = new ArrayList(slData.Values);
aList.Sort();

int MaxDuplicateCount = (int)aList[aList.Count - 1];

foreach (int Key in slData.Keys)
{
if (slData[Key].Equals(MaxDuplicateCount))
return Key;
}
return 0;
}

static void Main(string[] args)
{
TestAppLibrary objTest = new TestAppLibrary();
int[] intArray = new int[10];
intArray[0] = 100;
intArray[1] = 200;
intArray[2] = 100;
intArray[3] = 40;
intArray[4] = 100;
intArray[5] = 300;
intArray[6] = 100;
intArray[7] = 2100;
intArray[8] = 400;
intArray[0] = 400;

Console.WriteLine("Maximum Duplicate value: {0}", objTest.GetMaxDuplicateValue(intArray));
Console.ReadLine();
}
}

About admin

No description. Please complete your profile.
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.