So here is my array.
double[] testArray = new double[10];
// will generate a random numbers from 1-20, too lazy to write the code
I want to
int[] nums = new int[] { 1, 2, 3, 4, 5};
Console.WriteLine(AnyDuplicate(nums));
}
/// <summary>
/// Returns true if there is at least a duplicate in the array.
/// </summary>
/// <returns></returns>
static bool AnyDuplicate(int[] numbers)
{
for (int i = 0; i < numbers.Length; i++)
{
for (int j = i + 1; j < numbers.Length; j++)
{
if (numbers[i] == numbers[j])
{
return true;
}
}
}
return false;
You could do this with a little Linq:
if (testArray.Length != testArray.Distinct().Count())
{
Console.WriteLine("Contains duplicates");
}
The Distinct extension method removes any duplicates, and Count gets the size of the result set. If they differ at all, then there are some duplicates in the list.
Alternatively, here's more complicated query, but it may be a bit more efficient:
if (testArray.GroupBy(x => x).Any(g => g.Count() > 1))
{
Console.WriteLine("Contains duplicates");
}
The GroupBy method will group any identical elements together, and Any return true
if any of the groups has more than one element.
Both of the above solutions work by utilizing a HashSet<T>, but you can use one directly like this:
if (!testArray.All(new HashSet<double>().Add))
{
Console.WriteLine("Contains duplicates");
}
Or if you prefer a solution that doesn't rely on Linq at all:
var hashSet = new HashSet<double>();
foreach(var x in testArray)
{
if (!hashSet.Add(x))
{
Console.WriteLine("Contains duplicates");
break;
}
}