diff --git a/hashing.cpp b/hashing.cpp new file mode 100644 index 0000000..3b8dda2 --- /dev/null +++ b/hashing.cpp @@ -0,0 +1,71 @@ +#include + +using namespace std; + +template< + typename TElem, + std::size_t NSize> +class HashList { +private: + typedef struct { + std::size_t index; + TElem elem; + } entry; + + entry* entries[NSize]; + + std::size_t create_hash(std::size_t const index, std::size_t const e) { + return (index + e) % NSize; + } + +public: + HashList() { + for(std::size_t i = 0; i < NSize; i++) entries[i] = NULL; + } + bool insert(std::size_t index, TElem elem) { + std::size_t hash = 0; + std::size_t e = 0; + + for(; e < NSize; e++) { + hash = this->create_hash(index, e); + if(entries[hash] == NULL) break; + } + + printf("Inserting %d had %d collisions\n", index, e); + + if(entries[hash] != NULL) return false; + + entries[hash] = new entry{index,elem}; + return true; + } + + entry* find(std::size_t index) { + std::size_t hash = 0; + std::size_t e = 0; + for(; e < NSize; e++) { + hash = this->create_hash(index, e); + if(entries[hash] == NULL || entries[hash]->index == index) break; + } + printf("Finding %d had %d collisions\n", index, e); + + if(entries[hash] != NULL && entries[hash]->index != index) return NULL; + + return entries[hash]; + } + +}; + +int main( int argc, char *argv[] ) { + + HashList l; + + l.insert(1024, 2.5f); + l.insert(204, 1.5f); + l.insert(217, 1.0f); + + printf("1024: %.1f\n", l.find(1024)->elem); + printf("204: %.1f\n", l.find(204)->elem); + printf("217: %.1f\n", l.find(217)->elem); + + return 0; +}