Skip to content

Commit

Permalink
[cpp][17_skiplist] impl of random level, and its unit test.
Browse files Browse the repository at this point in the history
  • Loading branch information
Liam0205 committed Oct 31, 2018
1 parent c8a91ee commit de5fd9f
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
25 changes: 23 additions & 2 deletions c-cpp/17_skiplist/skiplist_tr.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,28 @@
#include <list>
#include <functional>
#include <type_traits>
#include <random>

namespace skiplist_detail {
template <typename Key, typename Value>
struct InternalNode {
const Key key;
std::multiset<Value> values;
using iterator = typename std::list<InternalNode>::iterator;
const Key key;
std::multiset<Value> values;
std::vector<iterator> forwards;
};

template <typename IntType>
class random_level {
private:
mutable std::random_device rd;
mutable std::mt19937 gen = std::mt19937(rd());
mutable std::binomial_distribution<IntType> dist;

public:
random_level(IntType max_level, double prob) : dist(max_level - 1, prob) {}
inline IntType operator()() const { return dist(gen); }
};
} // namespace skiplist_detail

template <typename Value,
Expand All @@ -36,6 +49,14 @@ class skiplist {
using iterator = typename container::iterator;
static_assert(std::is_same<iterator, typename node_type::iterator>::value,
"STATIC ASSERT FAILED! iterator type differs.");

private:
size_type max_lv_ = 16;
double prob_ = 0.5;
mutable random_level<size_type> rl_;

public:
skiplist() : rl_(max_lv_, prob_) {}
};

#endif // SKIPLIST_SKIPLIST_TR_HPP_
Expand Down
13 changes: 12 additions & 1 deletion c-cpp/17_skiplist/skiplist_tr_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,22 @@
*/

#include <iostream>
#include <map>
#include <string>

#include "skiplist_tr.hpp"

int main() {
std::cout << "hello world" << std::endl;
// 1. UT for skiplist_detail::random_level
skiplist_detail::random_level<size_t> rl(5, 0.5);
std::map<size_t, size_t> hist;
for (size_t i = 0; i != 10000; ++i) {
++hist[rl()];
}
for (auto p : hist) {
std::cout << p.first << ' ' << std::string(p.second / 100, '*') << '\n';
}

return 0;
}

0 comments on commit de5fd9f

Please sign in to comment.