CSharp · Console
using System;
using System.Diagnostics;
// Remove all duplicated elements from given array
// The order of remaining distinct elements does not matter.
public class Program
{
public static int InputInt(string prompt)
{
Console.Write("Enter " + prompt + ": ");
return Convert.ToInt32(Console.ReadLine());
}
public static void Main()
{
int n = InputInt("number of elements");
int [] a = new int[n];
Trace.Assert(n > 0);
for(int i=0; i < n ; i++)
{
a[i] = InputInt(string.Format("a[{0}]", i));
}
// invariant: elements a[0..n-1] contain same set of different values as original array and
// elements a[0..i-1] are unique within a[0..n-1]
for(int i=0; i<=n; i++)
{
// note: according to invariant, a[i] does not matcn with any of a[0..i-1]
// so it is enough to remove duplicates in a[i+1..n-1]
for(int k=i+1; k<n; k++)
{
if(a[i]==a[k])
{
for (int j=k;j<n-1;j++)
{
a[j] = a[j+1];
}
n--;
k--;
}
}
}
// elements a[0..n-1] contain same set of different values as original array and
// there are no duplicates
Console.WriteLine("a contains {0} distincs values", n);
for(int i=0; i < n ; i++)
{
Console.WriteLine("a[{0}]={1}", i, a[i]);
}
// Time = O(n*n*n)
}
}