Advertisement
Guest User

Untitled

a guest
Nov 15th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstring>
  3. #include <array>
  4. #include <list>
  5. #include <string>
  6. #include <algorithm>
  7.  
  8. using namespace std;
  9.  
  10. unsigned int mi_hash(string cadena) {
  11. unsigned int resultado = 1;
  12. for(int i = 0; i < cadena.length(); ++i) {
  13. resultado = 31 * resultado + cadena[i];
  14. }
  15. return resultado;
  16. }
  17.  
  18. class EstructuraHash {
  19. public:
  20. explicit EstructuraHash()
  21. : elementos(tamanoActual)
  22. {}
  23.  
  24. int tamanoActual = 100;
  25. float porcentajeAgraandado = 0.80;
  26.  
  27. vector<list<string>> elementos;
  28.  
  29. void agregar(string cadena) {
  30. unsigned int hash_resultado = mi_hash(cadena);
  31. unsigned int posicion = hash_resultado % 10;
  32. elementos.at(posicion).push_back(cadena);
  33.  
  34. auto usados = [](const vector<list<string>>& elementos) {
  35. int resultado = 0;
  36. for(auto bucket : elementos) {
  37. resultado += std::count_if(bucket.begin(), bucket.end(),
  38. [](std::string e) -> bool { return !e.empty(); });
  39. }
  40. return resultado;
  41. };
  42.  
  43. if(usados(elementos) > tamanoActual * porcentajeAgraandado) {
  44. realocar();
  45. }
  46. }
  47.  
  48. bool existe(std::string cadena) {
  49. unsigned int hash_resultado = mi_hash(cadena);
  50. unsigned int posicion = hash_resultado % 10;
  51. auto bucketList = elementos.at(posicion);
  52. auto elemento = std::find(bucketList.begin(), bucketList.end(), cadena);
  53.  
  54. return elemento != bucketList.end();
  55. }
  56.  
  57. void realocar() {
  58. vector<list<string>> viejoVector(tamanoActual*2);
  59. swap(viejoVector, elementos);
  60. for(auto bucket : viejoVector) {
  61. for(auto registro : bucket) {
  62. agregar(registro);
  63. }
  64. }
  65. }
  66. };
  67.  
  68.  
  69. int main()
  70. {
  71. EstructuraHash h;
  72. h.agregar("HelloWorld");
  73. h.agregar("Moby Dick");
  74. h.agregar("Bohemian rhapsody");
  75.  
  76. cout << h.existe("hi") << h.existe("Hello World");
  77. return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement