Generating the perfect hash function with a given list of strings?

Suppose I have a list of N lines known at compile time.

I want to generate (at compile time) a function that will display each line in a separate integer from 1 to N inclusive. A function should take up very little time or space to execute.

For example, suppose my lines are:

 {"apple", "orange", "banana"}

Such a function may return:

f("apple") -> 2
f("orange") -> 1
f("banana") -> 3

What is the strategy to create this feature?

I thought to parse strings at compile time and look for a couple of constants that I could put or add, or something else?

Compilation time generation time / space can be quite expensive (but obviously not so funny).

+4
source share
2 answers

, m , i, j - j- i- . , . , i, j , j & ge; | < > > |.

, , :

  • ( ) m - 1 , , .

  • -, -m -.


, - m-1 . . 1 . , : - 1 . , 0 , , , 1 .

, , m - 1 , ( , , log, m). , . . m , , . .

, m - 1 p 1,..., p m - 1. i, p j p j & ge; | a i |: .


h (a i) = & sum; j = 1 m - 1 [q j a i, p j% n], q j n. h -: P (x & ne; y & wedge; h (x) = h (y)) & le; 1/.


-, -. , m 2 h n = m 2 , . , , 2, , , .

+1

. 1 , 2 - ,... , .

, trie , .

0

Source: https://habr.com/ru/post/1658118/


All Articles