Josh
Josh

Reputation: 3321

Hashing Function for Map C++

I am trying to determine a hash function which takes an input (i, k) and determines a unique solution.

The possible inputs for (i, k) range from 0 to 100. Consider each (i, k) as a position of a node in a trinomial tree.

Ex: (0, 0) can diverge to (1, 1) (1, 0) (1, -1). 
    (1, 1) can diverge to (2, 2) (2, 1) (2, 0).

Sample given here:

http://www.google.com/imgres?imgurl=http://sfb649.wiwi.hu-berlin.de/fedc_homepage/xplore/tutorials/stfhtmlimg1156.gif&imgrefurl=http://sfb649.wiwi.hu-berlin.de/fedc_homepage/xplore/tutorials/stfhtmlnode41.html&h=413&w=416&sz=4&tbnid=OegDZu-yeVitZM:&tbnh=90&tbnw=91&zoom=1&usg=__9uQWDNYNLV14YioWWbrqPgfa3DQ=&docid=2hhitNyRWjI_DM&hl=en&sa=X&ei=xAfFUIbyG8nzyAHv2YDICg&ved=0CDsQ9QEwAQ

I am using a map

map <double, double> hash_table

I need a key value to be determined from pairs (i, k) to hash to to value for that (i, k)

So far I was only able to come up with linear functions such as: double Hash_function(int i, int k)

{
    //double val = pow(i, k) + i;
    //return (val % 4294967296);
    return (i*3.1415 + k*i*9.12341); 
}

However, I cannot determine a unique key with a certain (i, k). What kind of functions can I use to help me do so?

Upvotes: 0

Views: 1096

Answers (3)

Moshe Gottlieb
Moshe Gottlieb

Reputation: 4013

If i & k are 0-100, than your key can be a simple short (even signed) and is uniquely generated with something like short key = i | k << 8.

Upvotes: 0

Daniel Trebbien
Daniel Trebbien

Reputation: 39218

Mathematically speaking, you are seeking a bijection. This is not a hash function in the computer science sense because hash functions are expected to produce collisions on occasion (unless it is a perfect hash function).

What you have labeled hash_table is not a hash table. std::map is a different data structure called an ordered map, and it is able to use any key type for which the less-than operator < provides a strict weak ordering. You can, in fact, use std::pair from the utility header:

std::map<std::pair<int, int>, double> table;

To insert into the table, you would use:

table[std::make_pair(i, j)] = value;

Upvotes: 2

pt3dNyc
pt3dNyc

Reputation: 369

@Grizzly is correct that using double as a key is problematic. Maybe it would be better to use a string-based hashing technique?

Upvotes: 1

Related Questions