2013-03-27 88 views
1

首先,我想知道是否有人知道表示n維矢量的矢量的散列函數?矢量的散列函數<double>

其次,有沒有類似的散列函數,我可以指定一個分辨率,使兩個「關閉」向量散列到相同的值?

例如: 定分辨率R = 0.01 Q1 = {1.01,2.3} Q2 = {1.01,2.31} 將散列到相同的值。

感謝您的幫助!

+0

顧名思義,這不是散列函數。我想你可以爲每一個做floor(x * 10),然後使用正常的散列函數。 – 2013-03-27 04:52:00

回答

1

也許這樣的事情會對你有用嗎?

#include <stdint.h> 
#include <iostream> 
#include <vector> 

using namespace std; 

// simple variant of ELF hash ... but you could use any general-purpose hashing algorithm here instead 
static int GetHashCodeForBytes(const char * bytes, int numBytes) 
{ 
    unsigned long h = 0, g; 
    for (int i=0; i<numBytes; i++) 
    { 
     h = (h << 4) + bytes[i]; 
     if (g = h & 0xF0000000L) {h ^= g >> 24;} 
     h &= ~g; 
    } 
    return h; 
} 

static int GetHashForDouble(double v) 
{ 
    return GetHashCodeForBytes((const char *)&v, sizeof(v)); 
} 

static int GetHashForDoubleVector(const vector<double> & v) 
{ 
    int ret = 0; 
    for (int i=0; i<v.size(); i++) ret += ((i+1)*(GetHashForDouble(v[i]))); 
    return ret; 
} 

int main() 
{ 
    vector<double> vec; 
    vec.push_back(3.14159); 
    vec.push_back(2.34567); 
    cout << " Hash code for test vec is: " << GetHashForDoubleVector(vec) << endl; 
    return 0; 
}