Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_skipList.H
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
51# ifndef TPL_SKIPLIST_H
52# define TPL_SKIPLIST_H
53
54# include <climits>
55# include <ctime>
56# include <utility>
57# include <ah-random.H>
58# include <aleph.H>
59# include <ah-errors.H>
60
61namespace Aleph
62{
94 template <class Key, class Type>
96 {
97 public:
99 static const int maxLevel = 32;
100
102 static const double defaultProbability;
103
104 class Node
105 {
106 protected:
107 int level;
108
110
111 /*
112 Public methods work in function of nullptr pointer in order to indicate
113 unsuccessful conditions. We put NullPtr as private in order to avoid
114 that to accidentally put NullPtr instead of nullptr
115 */
116 static Node *NullPtr;
117
118 private:
119 Key key;
121
122 Node ** forward_ptr() noexcept
123 {
124 return reinterpret_cast<Node **>(reinterpret_cast<char *>(this) + sizeof(*this));
125 }
126
127 Node * const * forward_ptr() const noexcept
128 {
129 return reinterpret_cast<Node * const *>(
130 reinterpret_cast<const char *>(this) + sizeof(*this));
131 }
132
134 {
135 for (int i = 0; i < level; i++)
136 forward_ptr()[i] = const_cast<Node *>(&nodeSentinel);
137 }
138
139 public:
140 friend class SkipList<Key, Type>;
141
142 Node(const Key & _key, const Type & _data, int n)
143 : level(n),
144 key(_key),
145 data(_data)
146 {
147 /* EMPTY */
148 }
149
150 Node(const Key & _key, int n)
151 : level(n),
152 key(_key)
153 {
154 /* EMPTY */
155 }
156
157 Node(const int n)
158 : level(n)
159 {
160 /* EMPTY */
161 }
162
164 : level(0),
166 {
167 /* EMPTY */
168 }
169
170 ~Node() = default;
171
172 [[nodiscard]] Node * get_next() const noexcept
173 {
174 auto *next = forward_ptr()[0];
175 return (next == NullPtr) ? nullptr : next;
176 }
177
179 {
180 assert(i < level);
181 return forward_ptr()[i];
182 }
183
185 {
186 return forward_ptr();
187 }
188
189 [[nodiscard]] const Key &get_key() const noexcept { return key; }
190
191 Key &get_key() noexcept { return key; }
192
193 [[nodiscard]] const Type &get_data() const noexcept { return data; }
194
195 Type &get_data() noexcept { return data; }
196
197 [[nodiscard]] int getLevel() const noexcept { return level; }
198
201 static Key computeMaxKey() noexcept;
202
203 protected:
205 };
206
207 private:
208 /*
209 Headenode : it's used for header node,
210 it's an static array with maxLevel elements
211 */
212 class HeaderNode : public SkipList<Key, Type>::Node
213 {
214 private:
216
217 friend class SkipList<Key, Type>;
218
219 public:
221 {
222 this->level = maxLevel;
223
224 for (int i = 0; i < maxLevel; i++)
225 HeaderNode::forward[i] = Node::NullPtr;
226 }
227
229 {
230 assert(i < this->getLevel());
231 assert(this->getLevel() <= maxLevel);
232
233 return HeaderNode::forward[i];
234 }
235 };
236
237 /*
238 Node*& getForward(Node* p, int i)
239 {
240 if ( p == headerPtr )
241 return ((HeaderNode*) p)->HeaderNode::forward[ i ];
242 else
243 return p->Node::forward[ i ];
244 }
245 */
246
247 HeaderNode header; // SkipList's header
248 HeaderNode *headerPtr; // Pointer to header
249 Random_Source r; // random number generator
250 double probability; // probability for randomLevel
251 int level; // Current Maximum level of list linked
252
253 // The seed of the generator, modulo 2^32 - 1, as it was taken for GSL
254 static unsigned long generator_seed(const unsigned long seed) noexcept
255 {
256 return seed % static_cast<unsigned long>(Gsl_Compatible_Rng::max());
257 }
258
259 public:
269 void set_seed(unsigned long seed)
270 {
272 }
273
275 [[nodiscard]] Random_Source & random_source() noexcept { return r; }
276
279 [[nodiscard]] const Random_Source & random_source() const noexcept { return r; }
280
290 [[deprecated("it makes a Mersenne Twister in a list that has none: "
291 "use random_source(); it goes in 8.0.0")]]
292 [[nodiscard]] Gsl_Compatible_Rng & rng() { return r.mersenne_twister(); }
293
294# if ALEPH_WITH_GSL
303 [[deprecated("the generator is no longer of GSL: use random_source(); it goes in 8.0.0")]]
304 gsl_rng * gsl_rng_object() { return r.gsl(); }
305# endif
306
316 SkipList(unsigned long seed, double p = defaultProbability)
317 : headerPtr(&header),
318 r(Random_Source::Engine::Mersenne_Twister, generator_seed(seed)),
319 probability(p),
320 level(0)
321 {
322 assert(probability >= 0 and probability <= 1);
323 }
324
329 explicit SkipList(double p = defaultProbability)
330 : headerPtr(&header),
331 probability(p),
332 level(0)
333 {
334 assert(probability >= 0 and probability <= 1);
335 }
336
337 // Disable copy (owns its random number generator)
338 SkipList(const SkipList &) = delete;
339 SkipList & operator=(const SkipList &) = delete;
340
351 {
352 swap(other);
353 }
354
360 SkipList & operator=(SkipList && other) noexcept
361 {
362 swap(other);
363 return *this;
364 }
365
371 void swap(SkipList & other) noexcept
372 {
373 for (int i = 0; i < maxLevel; ++i)
374 std::swap(header.HeaderNode::forward[i], other.header.HeaderNode::forward[i]);
375 r.swap(other.r);
376 std::swap(probability, other.probability);
377 std::swap(level, other.level);
378 }
379
384 [[nodiscard]] Node * search(const Key & searchKey) noexcept
385 {
386 Node *x = headerPtr;
387
388 for (int i = level - 1; i >= 0; i--)
389 while (x->getForward(i)->get_key() < searchKey)
390 x = x->getForward(i);
391
392 x = x->getForward(0);
393
394 // Return nullptr if not found (either sentinel or different key)
395 if (x == Node::NullPtr || x->get_key() != searchKey)
396 return nullptr;
397
398 return x;
399 }
400
406 Node * insert(Node *p) noexcept
407 {
408 int i;
409 Node *update[maxLevel];
410 Node *x = headerPtr;
411
412 assert(p->getLevel() > 0 and p->getLevel() <= maxLevel);
413
414 p->fillForwardnullptr();
415
416 for (i = level - 1; i >= 0; i--)
417 {
418 while (x->getForward(i)->get_key() < p->get_key())
419 x = x->getForward(i);
420
421 update[i] = x;
422 }
423
424 x = x->getForward(0); // go to next node
425
426 if (p->getLevel() > level)
427 {
428 for (i = level; i < p->getLevel(); i++)
429 update[i] = headerPtr;
430 level = p->getLevel();
431 }
432
433
434 for (i = 0; i < p->getLevel(); i++)
435 {
436 p->getForward(i) = update[i]->getForward(i);
437 update[i]->getForward(i) = p;
438 }
439
440 assert(checkSkipList() == true);
441 return p;
442 }
443
446 [[nodiscard]] Node * get_first() noexcept
447 {
448 return headerPtr->HeaderNode::forward[0];
449 }
450
458 [[nodiscard]] int get_level() const noexcept { return level; }
459
471 [[nodiscard]] Node * remove(const Key & searchKey) noexcept
472 {
473 Node *update[maxLevel];
474 Node *x = headerPtr;
475 int i;
476
477 for (i = level - 1; i >= 0; i--)
478 {
479 while (x->getForward(i)->get_key() < searchKey)
480 x = x->getForward(i);
481 update[i] = x;
482 }
483
484 x = x->getForward(0);
485
486 // The sentinel has the key of computeMaxKey(), but it is not a node
487 // of the list, as search() knows
488 if (x != Node::NullPtr and x->get_key() == searchKey)
489 {
490 for (i = 0; i < level; i++)
491 {
492 if (update[i]->getForward(i) != x)
493 break;
494 update[i]->getForward(i) = x->getForward(i);
495 }
496
497 // The top level in use is level - 1, and an empty level ends at
498 // the sentinel, not at nullptr
499 while (level > 0 and headerPtr->getForward(level - 1) == Node::NullPtr)
500 level--;
501 }
502 else
503 return nullptr;
504
505 assert(checkSkipList() == true);
506
507 return x;
508 }
509
514 [[nodiscard]] int generateRandomLevel() noexcept
515 {
516 int l = 1;
517 assert(probability > 0 and probability < 1);
518 while (r.uniform() < probability and l < maxLevel)
519 ++l;
520 return l;
521 }
522
526 [[nodiscard]] bool checkSkipList() const noexcept
527 {
528 Node *node = header.get_next();
529 while (node != nullptr)
530 {
531 if (node->get_next() == nullptr)
532 break;
533
534 if (node->get_key() > node->get_next()->get_key())
535 return false;
536 node = node->get_next();
537 }
538 return true;
539 }
540
542 [[nodiscard]] Node * new_node() noexcept { return nullptr; }
543
557 {
558 const SkipList *list_ptr = nullptr;
559 Node *curr = nullptr;
560
561 public:
563
565 Iterator() noexcept = default;
566
567 Iterator(const Iterator &) noexcept = default;
568
571 Iterator(const SkipList & list) noexcept
572 : list_ptr(&list), curr(list.headerPtr->HeaderNode::forward[0])
573 {
574 // Skip sentinel if we landed on it
575 if (curr == Node::NullPtr)
576 curr = nullptr;
577 }
578
581 [[nodiscard]] bool has_curr() const noexcept { return curr != nullptr; }
582
584 [[nodiscard]] bool is_last() const noexcept
585 {
586 if (curr == nullptr)
587 return false;
588 Node *next = curr->get_next();
589 return next == nullptr;
590 }
591
595 [[nodiscard]] Node * get_curr() const
596 {
597 ah_overflow_error_if(curr == nullptr) << "SkipList::Iterator::get_curr(): no current";
598
599 return curr;
600 }
601
604 [[nodiscard]] Node * get_curr_ne() const noexcept { return curr; }
605
607 [[nodiscard]] const Key &get_key() const { return get_curr()->get_key(); }
608
610 [[nodiscard]] const Type &get_data() const { return get_curr()->get_data(); }
611
613 void next()
614 {
615 ah_overflow_error_if(curr == nullptr) << "SkipList::Iterator::next(): no current";
616 next_ne();
617 }
618
620 void next_ne() noexcept
621 {
622 if (curr != nullptr)
623 {
624 curr = curr->get_next();
625 // get_next() returns nullptr for sentinel, so we're done
626 }
627 }
628
630 void reset_first() noexcept
631 {
632 if (list_ptr != nullptr)
633 {
634 curr = list_ptr->headerPtr->HeaderNode::forward[0];
635 if (curr == Node::NullPtr)
636 curr = nullptr;
637 }
638 }
639
641 void reset() noexcept { reset_first(); }
642
644 Iterator &operator=(const Iterator & it) noexcept
645 {
646 list_ptr = it.list_ptr;
647 curr = it.curr;
648 return *this;
649 }
650
652 [[nodiscard]] bool operator==(const Iterator & it) const noexcept
653 {
654 return curr == it.curr;
655 }
656
658 [[nodiscard]] bool operator!=(const Iterator & it) const noexcept
659 {
660 return curr != it.curr;
661 }
662
665 {
666 next_ne();
667 return *this;
668 }
669
671 Iterator operator++(int) noexcept
672 {
673 Iterator ret = *this;
674 next_ne();
675 return ret;
676 }
677
679 [[nodiscard]] Node * operator*() const { return get_curr(); }
680
682 [[nodiscard]] Node * operator->() const { return get_curr(); }
683 };
684
686 [[nodiscard]] Iterator begin() const noexcept { return Iterator(*this); }
687
689 [[nodiscard]] Iterator end() const noexcept { return Iterator(); }
690 };
691
692 /*
693 BEWARE: Ensure that this instantiation to be unique
694 */
695 template <class Key, class Type>
696 typename SkipList<Key, Type>::Node SkipList<Key, Type>::Node::nodeSentinel;
697
698 template <class Key, class Type>
699 typename SkipList<Key, Type>::Node *SkipList<Key, Type>::Node::NullPtr =
700 &SkipList<Key, Type>::Node::nodeSentinel;
701
702
703 template <class Key, class Type>
705} // end namespace Aleph
706
707# endif // TPL_SKIPLIST_H
Exception handling system with formatted messages for Aleph-w.
#define ah_overflow_error_if(C)
Throws std::overflow_error if condition holds.
Definition ah-errors.H:611
The random number generators of Aleph: the one that gives the numbers of the gsl_rng_mt19937 of GSL,...
Core header for the Aleph-w library.
A random number generator with the sequences of GSL's gsl_rng_mt19937.
Definition ah-random.H:147
static constexpr result_type max() noexcept
The greatest number of operator()(): 2^32 - 1.
Definition ah-random.H:259
The source of random numbers of a randomized structure, which draws from one of two generators.
Definition ah-random.H:883
@ Mersenne_Twister
A Gsl_Compatible_Rng, in dynamic memory.
Gsl_Compatible_Rng & mersenne_twister()
The Mersenne Twister of the source, which is its engine from now on.
Definition ah-random.H:1087
double uniform() noexcept
A real number in [0, 1).
Definition ah-random.H:1181
void seed(const std::uint64_t s) noexcept
Draws from now on from the SplitMix64 of a seed.
Definition ah-random.H:1040
void swap(Random_Source &o) noexcept
Swaps the generators, with their states.
Definition ah-random.H:1021
SkipList< Key, Type >::Node * forward[maxLevel]
Iterator for traversing SkipList elements in ascending order.
const Type & get_data() const
Get current data (throws if no current).
Node * operator->() const
Arrow operator (returns node pointer).
Iterator & operator=(const Iterator &it) noexcept
Assignment operator.
bool is_last() const noexcept
Check if iterator is on the last element.
Iterator operator++(int) noexcept
Postfix increment operator.
bool operator==(const Iterator &it) const noexcept
Equality comparison.
Iterator() noexcept=default
Default constructor (invalid iterator).
void next_ne() noexcept
Advance to next element without exception check.
Node * get_curr() const
Get current node (throws if no current).
Node * operator*() const
Dereference operator (returns node pointer).
Iterator & operator++() noexcept
Prefix increment operator.
bool has_curr() const noexcept
Check if iterator has a current element.
void next()
Advance to next element (throws if no current).
void reset_first() noexcept
Reset iterator to first element.
Node * get_curr_ne() const noexcept
Get current node without exception check.
const Key & get_key() const
Get current key (throws if no current).
void reset() noexcept
Reset iterator to first element (alias).
bool operator!=(const Iterator &it) const noexcept
Inequality comparison.
Node(const Key &_key, const Type &_data, int n)
Node(const Key &_key, int n)
Node * get_next() const noexcept
Node *& getForward(int i)
Key & get_key() noexcept
const Key & get_key() const noexcept
int getLevel() const noexcept
Node ** forward_ptr() noexcept
static Key computeMaxKey() noexcept
Compute the maximum possible key value (used for sentinel).
Node *const * forward_ptr() const noexcept
static Node * NullPtr
Type & get_data() noexcept
const Type & get_data() const noexcept
Skip List - a probabilistic ordered data structure.
int get_level() const noexcept
Return the level of the list: the number of levels in use.
Node * get_first() noexcept
Get the first node in the list.
bool checkSkipList() const noexcept
Verify skip list invariants (for debugging).
Node * remove(const Key &searchKey) noexcept
Remove a key from the skip list.
static const int maxLevel
Maximum level for any node (supports up to 2^32 elements efficiently)
int generateRandomLevel() noexcept
Generate a random level for a new node.
Random_Source r
Gsl_Compatible_Rng & rng()
The Mersenne Twister of the list, which a list that was given no seed makes here, and draws from it f...
Iterator begin() const noexcept
Get iterator to first element.
void set_seed(unsigned long seed)
Seeds the Mersenne Twister of the list, as gsl_rng_set() did: the levels are from then on those of GS...
SkipList(SkipList &&other)
Take the nodes and the generator of another list, which is left empty, and draws from then on from a ...
SkipList & operator=(SkipList &&other) noexcept
Exchange this list with another, which is left with the previous nodes and generator of this one.
Random_Source & random_source() noexcept
The source of random numbers, which draws the levels.
static unsigned long generator_seed(const unsigned long seed) noexcept
SkipList(const SkipList &)=delete
Node * search(const Key &searchKey) noexcept
Search for a key in the skip list.
void swap(SkipList &other) noexcept
Exchange the nodes, the generators and the probabilities of this list and another.
HeaderNode * headerPtr
static const double defaultProbability
Default probability for level generation (0.5 = geometric distribution)
Iterator end() const noexcept
Get iterator past the last element.
SkipList(double p=defaultProbability)
Construct a SkipList that draws its levels from a SplitMix64 with a seed of its own,...
SkipList(unsigned long seed, double p=defaultProbability)
Construct a SkipList with given seed and probability, whose levels are those of GSL for the seed: it ...
Node * new_node() noexcept
Placeholder for node allocation (override in derived classes).
const Random_Source & random_source() const noexcept
The source of random numbers, to look at it: its engine, or whether it is equal to another one.
HeaderNode header
Node * insert(Node *p) noexcept
Insert a node into the skip list.
SkipList & operator=(const SkipList &)=delete
Main namespace for Aleph-w library functions.
auto get_curr() const
Return the current tuple (bounds-checked).
Definition ah-zip.H:192
and
Check uniqueness with explicit hash + equality functors.
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
void next_ne() noexcept(noexcept(std::declval< Aleph::const_iterator_t< HeadC > & >().next_ne()) and noexcept(std::declval< ZipIterator< TailC... > & >().next_ne()))
Advance all underlying iterators (unchecked variant).
Definition ah-zip.H:252
ValueArg< size_t > seed
Definition testHash.C:53
DynList< int > l