Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute hash function in range 0..n

Tags:

algorithm

hash

I have an array of strings. Array has length n. How to compute hash key for each string, so each key will be a number in range of 0..n?

UPDATE

Array's items could be not strings, but numbers if it will helps to someone to help me ;)

like image 234
Kornel William Avatar asked Apr 30 '26 16:04

Kornel William


1 Answers

Try modulo N:

int N = array.Length;
int hashMaxN = strings[i].GetHashCode() % N;

This will not guarantee unique hashes for different indices. But a hash code isn't unique.

If you want a unique id assigned to each string in a list, then use the suggestion from anothe r answer: pick the strings index in the sorted array of distinct strings

int itemHash = myList.Distinct().OrderBy(s => s).IndexOf(item);

This will have the property of being the same for the same string regardless of how the list is ordered but adding a string to the list will change the hash codes for the items.

like image 169
Anders Forsgren Avatar answered May 03 '26 08:05

Anders Forsgren