geo_hash.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. #ifndef _GEO_HASH__
  2. #define _GEO_HASH__
  3. #include "point.h"
  4. #include <iostream>
  5. #include <map>
  6. #include <vector>
  7. #include <algorithm>
  8. #include <tuple>
  9. #include <boost/container/flat_set.hpp>
  10. #include <string>
  11. NAMESPACE_POINT_BEGIN(NAMESPACE_POINT)
  12. struct ghash
  13. {
  14. static std::tuple<int,int> decode(unsigned h)
  15. {
  16. const unsigned S=0x80000000;
  17. int x=0,y=0;
  18. for(int i=0;i<16;i++)
  19. {
  20. x<<=1;
  21. y<<=1;
  22. if(h&S)
  23. x|=1;
  24. h<<=1;
  25. if(h&S)
  26. y|=1;
  27. h<<=1;
  28. }
  29. return std::make_tuple(x-32768,y-32768);
  30. }
  31. static unsigned encode(int x, int y)
  32. {
  33. return encode_(x+32768,y+32768);
  34. }
  35. public: //test
  36. static void test_code(int x,int y)
  37. {
  38. unsigned h=ghash::encode(x,y);
  39. auto t=ghash::decode(h);
  40. printf("src x=%X,y=%X hash=%X,check x=%X,y=%X\n",x,y,h,std::get<0>(t),std::get<1>(t));
  41. }
  42. static void test()
  43. {
  44. for(int i=0;i<10;i++)
  45. {
  46. test_code((4<<i)-1,(4<<i)-1);
  47. test_code((4<<i)-1,(4<<i));
  48. test_code((4<<i)-1,(4<<i)-1);
  49. test_code((4<<i),(4<<i)-1);
  50. }
  51. }
  52. private:
  53. static unsigned encode_(unsigned short x, unsigned short y)
  54. {
  55. const unsigned S=0x8000;
  56. unsigned r=0;
  57. for(int i=0;i<16;i++)
  58. {
  59. r<<=2;
  60. if(x&S)
  61. {
  62. r|=(y&S)?3:2;
  63. }
  64. else
  65. {
  66. if(y&S) r|=1;
  67. }
  68. x<<=1;
  69. y<<=1;
  70. }
  71. return r;
  72. }
  73. };
  74. struct geo_list
  75. {
  76. private:
  77. std::multimap<unsigned int,std::string> geo2card;
  78. std::map<std::string,unsigned int> card2geo;
  79. inline void find_near(std::vector<std::string>&ret,int x,int y,unsigned h,int dist2,unsigned mask,const std::string & card_no);
  80. public:
  81. std::vector<std::string> find_near(int x,int y,int dist,const std::string & card_no);
  82. //std::vector<std::string> find_near(const char*card_no,int dist)
  83. std::vector<std::string> find_near(const std::string& card_no,int dist);
  84. //void update(int x,int y,const char*card_no)
  85. void update(int x,int y,const std::string card_no);
  86. size_t size()
  87. {
  88. return card2geo.size();
  89. }
  90. void print()
  91. {
  92. for(auto it=card2geo.begin();it!=card2geo.end();++it)
  93. {
  94. std::cout<<it->first<<"\n";
  95. }
  96. }
  97. geo_list()
  98. {
  99. }
  100. ~geo_list()
  101. {
  102. }
  103. };
  104. NAMESPACE_POINT_END(NAMESPACE_POINT)
  105. #endif