geo_hash.h 1.9 KB

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