Saturday, July 6, 2013

Removing Duplicate Numbers from User Defined Array

Okay, so I've created an array that is defined by the user input, they enter a number to determine the amount of elements, then they put in the value of said elements. My program is supposed to remove duplicates from this array. This is what I have so far, it runs, but not how I want it to. This is what I have so far, however I am missing something or I added something extra. Can someone explain what I'm doing wrong?

` static void Main()

{

Console.WriteLine("enter array length ");

int number = Int32.Parse(Console.ReadLine());


int[] number1 = new int[number];


int[] number2 = ElimDuplicates(number1); // array to eliminate duplicates


foreach (int duplicate in number2)
{

Console.Write("{0}, ", duplicate);
}
Console.WriteLine();
Console.ReadLine();
}
/// <summary>
/// Eliminates the Duplicates
/// </summary>
/// <param name="number"></param>
/// <returns></returns>
static int[] ElimDuplicates(int[] number)
{
if (number == null || number.Length == 1)
{
return number;
}

ArrayList list = new ArrayList(number);
list.Sort();
for (int i = list.Count - 1; i > 0; i--)
{
if ((int)list[i] == (int)list[i - 1]) list.RemoveAt(i);
}
return (int[])list.ToArray(typeof(int));
}


public static void GetArray(int[] array)
{

for (int count = 0; count < array.Length; count++)
{
Console.WriteLine("enter a number:");
array[count] = Convert.ToInt32(Console.ReadLine());
}
}
}

}


` - Full Post

No comments:

Post a Comment