using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
var la = new List<int>() { 1, 0, 4, 200, -40 };
var lb = new List<int>() { -40, 200, 4, 1, 0 };
var lc = new List<int>() { 3, 5, 4, 9, 11 };
var ld = new List<int>() { 6, 6, 100 };
var le = new List<int>() { 6, 100, 100 };
Console.WriteLine(UnorderedEqual(la, lb));
Console.WriteLine(UnorderedEqual(la, lc));
Console.WriteLine(UnorderedEqual(lc, ld));
Console.WriteLine(UnorderedEqual(ld, le));
var a1 = new int[] { 1, 2, 5 };
var a2 = new int[] { 2, 5, 1 };
var a3 = new int[] { 1, 1, 3 };
var a4 = new int[] { 3, 3, 1 };
Console.WriteLine(UnorderedEqual(a1, a2));
Console.WriteLine(UnorderedEqual(a1, a3));
Console.WriteLine(UnorderedEqual(a3, a4));
}
static bool UnorderedEqual<T>(ICollection<T> a, ICollection<T> b)
{
// Require that the counts are equal.
if (a.Count != b.Count)
{
return false;
}
// Initialize new Dictionary of the type.
var d = new Dictionary<T, int>();
// Add each key's frequency from collection A to the Dictionary.
foreach (T item in a)
{
int c;
if (d.TryGetValue(item, out c))
{
d[item] = c + 1;
}
else
{
d.Add(item, 1);
}
}
// Add each key's frequency from collection B to the Dictionary.
// ... Return early if we detect a mismatch.
foreach (T item in b)
{
int c;
if (d.TryGetValue(item, out c))
{
if (c == 0)
{
return false;
}
else
{
d[item] = c - 1;
}
}
else
{
// Not in dictionary
return false;
}
}
// Verify that all frequencies are zero.
foreach (int v in d.Values)
{
if (v != 0)
{
return false;
}
}
// We know the collections are equal.
return true;
}
}
True
False
False
False
True
False
False