小组成员: 曹可心-10223903406 朴祉燕-10224602413
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

59 Zeilen
2.0 KiB

  1. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  4. #ifndef STORAGE_LEVELDB_UTIL_RANDOM_H_
  5. #define STORAGE_LEVELDB_UTIL_RANDOM_H_
  6. #include <stdint.h>
  7. namespace leveldb {
  8. // A very simple random number generator. Not especially good at
  9. // generating truly random bits, but good enough for our needs in this
  10. // package.
  11. class Random {
  12. private:
  13. uint32_t seed_;
  14. public:
  15. explicit Random(uint32_t s) : seed_(s & 0x7fffffffu) { }
  16. uint32_t Next() {
  17. static const uint32_t M = 2147483647L; // 2^31-1
  18. static const uint64_t A = 16807; // bits 14, 8, 7, 5, 2, 1, 0
  19. // We are computing
  20. // seed_ = (seed_ * A) % M, where M = 2^31-1
  21. //
  22. // seed_ must not be zero or M, or else all subsequent computed values
  23. // will be zero or M respectively. For all other values, seed_ will end
  24. // up cycling through every number in [1,M-1]
  25. uint64_t product = seed_ * A;
  26. // Compute (product % M) using the fact that ((x << 31) % M) == x.
  27. seed_ = static_cast<uint32_t>((product >> 31) + (product & M));
  28. // The first reduction may overflow by 1 bit, so we may need to
  29. // repeat. mod == M is not possible; using > allows the faster
  30. // sign-bit-based test.
  31. if (seed_ > M) {
  32. seed_ -= M;
  33. }
  34. return seed_;
  35. }
  36. // Returns a uniformly distributed value in the range [0..n-1]
  37. // REQUIRES: n > 0
  38. uint32_t Uniform(int n) { return Next() % n; }
  39. // Randomly returns true ~"1/n" of the time, and false otherwise.
  40. // REQUIRES: n > 0
  41. bool OneIn(int n) { return (Next() % n) == 0; }
  42. // Skewed: pick "base" uniformly from range [0,max_log] and then
  43. // return "base" random bits. The effect is to pick a number in the
  44. // range [0,2^max_log-1] with exponential bias towards smaller numbers.
  45. uint32_t Skewed(int max_log) {
  46. return Uniform(1 << Uniform(max_log + 1));
  47. }
  48. };
  49. }
  50. #endif // STORAGE_LEVELDB_UTIL_RANDOM_H_