using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
public class Test
{
public static void Main()
{
TimeSolution(new HashSetSolution());
TimeSolution(new OriginalSolution());
}
private static void TimeSolution(ISolution solution)
{
Random random = new Random(7);
var sw = new Stopwatch();
var count = 0;
const int iterations = 1000;
const int arraySize = 5000;
for (int i = 0; i < iterations; i++)
{
var input = GetRandomArray(arraySize, random);
var shuffled = new int[arraySize];
Array.Copy(input, shuffled, arraySize);
Shuffle(input, random);
sw.Start();
var areEqual = solution.SetEqual(input, shuffled, null);
sw.Stop();
if (areEqual)
{
count++;
}
}
Console.WriteLine("{0} / {1}: {2}", count, iterations, sw.Elapsed);
}
private static int[] GetRandomArray(int size, Random random)
{
int[] result = new int[size];
for (int i = 0; i < size; i++)
{
result[i] = random.Next();
}
return result;
}
private static void Shuffle(int[] input, Random random)
{
for (int i = input.Length - 1; i > 0; i--)
{
var j = random.Next(i + 1);
var swap = input[i];
input[i] = input[j];
input[j] = swap;
}
}
interface ISolution
{
bool SetEqual<T>(IEnumerable<T> source, IEnumerable<T> other, IEqualityComparer<T> comparer);
}
class HashSetSolution : ISolution
{
public bool SetEqual<T>(IEnumerable<T> source, IEnumerable<T> other, IEqualityComparer<T> comparer = null)
{
if (source == null) {
throw new ArgumentNullException("source");
}
if (other == null) {
throw new ArgumentNullException("other");
}
return new HashSet<T>(source, comparer).SetEquals(other);
}
}
class OriginalSolution : ISolution
{
public bool SetEqual<T>(IEnumerable<T> source, IEnumerable<T> other, IEqualityComparer<T> comparer = null)
{
if (source == null) {
throw new ArgumentNullException("source");
}
if (other == null) {
throw new ArgumentNullException("other");
}
ICollection<T> sourceCollection = source as ICollection<T> ?? source.ToArray();
ICollection<T> otherCollection = other as ICollection<T> ?? other.ToArray();
if (sourceCollection.Count != otherCollection.Count) {
return false;
}
if (sourceCollection.Except(otherCollection, comparer).Any()) {
return false;
}
if (otherCollection.Except(sourceCollection, comparer).Any()) {
return false;
}
return true;
}
}
}