C
C#12mo ago
Arch Leaders

Best way to uniquely hash an array of undefined length?

I need to recursively hash a tree of arrays/dicts, is there a preferred/best way to hash the values quickly? Essentially I need to cache equality, the idea being to hash every array in the tree once and lookup the object pointer, otherwise I'd have to generate the hash many times when comparing the arrays. If there's a better way to achieve that entirely, I'm open to that too.
4 Replies
Arch Leaders
Arch LeadersOP12mo ago
(The array is an array of arrays, the arrays hash will be made up of the contained arrays hashes) Would something like this work?
int hash = 17;
foreach (var item in this) {
// item.GetValueHash() recurses into this function
hash = hash * 23 + item.GetValueHash();
}

return hash;
int hash = 17;
foreach (var item in this) {
// item.GetValueHash() recurses into this function
hash = hash * 23 + item.GetValueHash();
}

return hash;
I hope it's never reached, but the length will never exceed 16,777,215 (UInt24)
jcotton42
jcotton4212mo ago
HashCode Struct (System)
Combines the hash code for multiple values into a single hash code.
jcotton42
jcotton4212mo ago
@Arch Leaders
Arch Leaders
Arch LeadersOP12mo ago
Thanks

Did you find this page helpful?