Perl Monk, Perl Meditation | |
PerlMonks |
RFC: Is there a solution to the flaw in my hash mechanism? (And are there any others?)by BrowserUk (Patriarch) |
on May 30, 2015 at 09:44 UTC ( [id://1128382]=perlquestion: print w/replies, xml ) | Need Help?? |
BrowserUk has asked for the wisdom of the Perl Monks concerning the following question: In Re^6: Heap structure for lookup?, I posted the bare bones of a very lightweight hash algorithm that is to be used for lookup purposes only. The basis of that algorithm is (I think this is the correct mathematical term) co-primality. Size the underlying array to that of a prime number somewhat bigger than the number of elements you want to store in the hash -- I chose 200,000,033 for my tests. To insert an element, calculate the hash function -- or in my case, use the value of the 64-bit integer as the hash --, calculate the insertion point as i = hash % PRIME;, and attempt the insertion. If that slot is already occupied, add the prime number to the previously calculated insertion point and again take the result mod PRIME: i = ( i + PRIME ) % PRIME; and try again. This simple mechanism has the rather nice property that it will eventually try every possible location before returning to the starting point -- which if it happened would indicate that the array is completely full. A second nice property is that the steps by which it jumps around the array are different for every initial insertion point; thus (probabilistically) avoiding excessive clustering. To demonstrate with small numbers. An array size 17:
The flaw with that is the first row. If the (initial_hash_value % PRIME ) = 0;, then the scheme falls apart and the second and all subsequent hash%prime == 0 values can never be stored. The code I posted incorporated an iteration count (c), that defended against an infinite loop; but it doesn't address the problem. My first thought was to size the array 1 larger than the chosen prime, and add 1 to the mod'd value; thus the zeroth element is never used; but that just results in an infinite loop of 1s rather than 0s. Is there a trivial (or not so) solution to the problem that I'm missing? Are there any other problems I'm missing? With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
I'm with torvalds on this
In the absence of evidence, opinion is indistinguishable from prejudice. Agile (and TDD) debunked
Back to
Seekers of Perl Wisdom
|
|