Given a set of integers, a "functional group", is there a better way to GetHashCode of the integers where the positions of the numbers doesn't affect the hash?
Sample code: https://dotnetfiddle.net/XoIN19#
static public void Main()
{
int[] ints = { 10001, 10002, 10003, 10004, 10005 };
int[] intsX = ints.Reverse().ToArray();
int hash1;
int hash2;
Func<int[], int> GetHashCode = new Func<int[], int>(x => GetHashCodeFlawed(x));
hash1 = GetHashCode(ints);
Console.WriteLine("hash1={0}", hash1); //954101523
hash2 = GetHashCode(intsX);
Console.WriteLine("hash2={0}", hash2); //957855123
Console.WriteLine("hash1==hash2 : {0}", hash1 == hash2);
}
static int GetHashCodeFlawed(IEnumerable<int> integers)
{
IEnumerator<int> intEnum = integers.GetEnumerator();
if(intEnum.MoveNext()==false) return 0;
int hash = 0;
unchecked {
hash = intEnum.Current.GetHashCode();
for(;intEnum.MoveNext()==true;)
hash = 31 * hash + intEnum.Current.GetHashCode();
}
return hash;
}
Output of this is: hash=954101523 If I swap 10003 and 10002 i get: hash=954130353
Besides sorting the list before getting the hash, is there a better alternative that wont change if the items in the list positions change?
The list of integers basically represents a set of record Ids that are a "functional group", so the "functional group" is really the key, and not really dependent on the order