Friday, February 12, 2016

Persistent dynamic set implementation

        We some times need to maintain past version of a dynamic set. One way to do this is to copy the  entire set each time it's modified, but this solution is very slow and consumes Θ(n) memory. Using a binary search tree we can do much better. We just need to copy a simple path from the root to the added or deleted element, therefore only consuming Θ(h)  memory (h being the height).  For this we need to get rid of the parent node, since each node can have several parent from different states of the tree. 

        This implementation is a Red Black Tree so we need the parent node, but the use of a stack or a queue can solve this problem. Since the tree is balanced any modifications only consumes Θ(lg(n)) memory.
Client example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int main()
{
    dts::PersistentSet<int, std::greater<int>> set;

    std::vector<std::function<bool(int)>> vec
    {
        [&](int x) { return set.add(x); },
        [&](int x) { return set.remove(x); }
    };

    for (unsigned j = 0; j < 300; ++j)
    {
        for (int i = 0; i < 200; ++i)
            vec[j % 2](rand() % 30);
    }
    for (unsigned i = 0; i < set.history_size(); ++i)
    {
        std::for_each(set.begin(i), set.end(), [](int x) {std::cout << x << ",";});
        std::cout << std::endl;
    }

    set.roll_back();
    return 0;
}

Persistent set:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
#pragma once

#include <functional>
#include <utility>
#include <iostream>
#include <stack>
#include <memory>
#include <deque>
#include <iterator>     
#include <type_traits>  
#include <stack>
#include <stdexcept>
#include <vector>

namespace dts
{

    template <typename T, typename Func = std::less<T>>
    class PersistentSet
    {

    public:

        PersistentSet();
        PersistentSet(Func);


        bool add(const T&);
        bool add(T&&);

        bool remove(const T&);

        bool empty() const;

        size_t history_size() const;

        void roll_back();

        class TreeIterator
            : public std::iterator<std::forward_iterator_tag,
            std::remove_cv_t<T>,
            std::ptrdiff_t,
            const T*,
            const T&>
        {
            using node = typename dts::PersistentSet<  
                                                        std::remove_cv_t<T>,
                                                        Func 
                                                    >::Nodeptr;
            
            node itr;
            node nil;
            std::stack<node> path;

            node find_successor(node n)
            {
                n = n->right;
                if (n != nil)
                {
                    while (n->left != nil)
                    {
                        path.push(n);
                        n = n->left;
                    }
                }
                else
                {
                    n = path.top();
                    path.pop();
                }
                return n;
            }
        public:

            explicit TreeIterator(node n, node pnil) : nil(pnil) //begin
            {
                if (n == nil)
                    itr = nil;
                else
                {
                    path.push(nil);
                    while (n->left != nil)
                    {
                        path.push(n);
                        n = n->left;
                    }
                    itr = n;
                }
            }
            explicit TreeIterator(node pnil) // end
                : itr(pnil), nil(pnil)
            { }


            TreeIterator& operator++ ()
            {
                itr = find_successor(itr);
                return *this;
            }
            TreeIterator operator++ (int)
            {
                TreeIterator tmp(*this);
                itr = find_successor(itr);
                return tmp;
            }

            bool operator == (const TreeIterator& rhs) const
            {
                return itr == rhs.itr;
            }

            bool operator != (const TreeIterator& rhs) const
            {
                return itr != rhs.itr;
            }

            const T& operator* () const
            {
                return itr->key;
            }

            const T& operator-> () const
            {
                return itr->key;
            }

        };


        typedef TreeIterator const_iterator;

        const_iterator begin() const
        {
            return begin(roots.size() - 1);
        }
        const_iterator begin(size_t index) const
        {
            if (index >= roots.size())
                throw std::out_of_range("out of range");

            return const_iterator(roots[index], nil);
        }
        const_iterator end() const
        {
            return const_iterator(nil);
        }

    private:

        struct Node;
        using Nodeptr = std::shared_ptr<Node>;

        struct Node
        {
            T key;
            bool isRed;

            Nodeptr left;
            Nodeptr right;

            Node(const T& pkey, bool pisRed, Nodeptr pleft, Nodeptr pright)
                : key(pkey), isRed(pisRed), left(pleft), right(pright)
            { }

            Node(T&& pkey, bool pisRed, Nodeptr pleft, Nodeptr pright)
                : key(std::move(pkey)), isRed(pisRed), left(pleft), right(pright)
            { }
        };

        std::vector<Nodeptr> roots;
        Func cmp;
        Nodeptr nil;

        template <typename TT>
        Nodeptr create_node(TT&&);

        Nodeptr copy_node(Nodeptr) const;

        template <typename TT>
        bool generic_add(TT&&);

        template <typename TT>
        Nodeptr add_recursive(std::deque<Nodeptr>&, TT&&, Nodeptr&);

        void balance_add(std::deque<Nodeptr> &x);

        template <typename ChildA, typename ChildB>
        void mirror_add_balance(Nodeptr&, Nodeptr&, std::deque<Nodeptr>&, ChildA, ChildB);

        Nodeptr remove_recursive(const T&, Nodeptr, std::deque<Nodeptr>&);

        template<typename F, typename NF, typename TT>
        Nodeptr find_and_build(TT&&, Nodeptr, std::deque<Nodeptr>&, F, NF);

        void delete_node(std::deque<Nodeptr> &);

        Nodeptr build_min_path(Nodeptr node, std::deque<Nodeptr>&);

        void transplant(Nodeptr, Nodeptr, Nodeptr);

        void balance_remove(Nodeptr x, std::deque<Nodeptr>&);

        template <typename ChildA, typename ChildB >
        void mirror_remove_balance(Nodeptr&, Nodeptr&, std::deque<Nodeptr> &, ChildA, ChildB);

        template <typename ChildA, typename ChildB >
        Nodeptr rotate(Nodeptr, Nodeptr, ChildA, ChildB);

        static Nodeptr& left(Nodeptr x) 
        { 
            return x->left; 
        };

        static Nodeptr& right(Nodeptr x) 
        { 
            return x->right; 
        };

        static Nodeptr pop_front(std::deque<Nodeptr>& deque)
        {
            auto front = deque.front();
            deque.pop_front();
            return front;

        };



    };

    template<typename T, typename Func>
    size_t  PersistentSet<T, Func>::history_size() const
    {
        return roots.size();
    }
    template<typename T, typename Func>
    bool PersistentSet<T, Func>::empty() const
    {
        return roots.back() == nil;
    }

    template<typename T, typename Func>
    void  PersistentSet<T, Func>::roll_back()
    {
        if (!roots.empty())
            roots.pop_back();
    }

    template <typename K, typename Func>
    void PersistentSet<K, Func>::transplant(

        Nodeptr parent,
        Nodeptr removed,
        Nodeptr transplanted)
    {
        if (parent == nil)
        {
            roots.pop_back();
            roots.push_back(transplanted);
        }
        else if (parent->left == removed)
            parent->left = transplanted;
        else
            parent->right = transplanted;
    }


    template<typename T, typename Func>
    PersistentSet<T, Func>::PersistentSet() : PersistentSet(Func())
    { }

    template<typename T, typename Func>
    PersistentSet<T, Func>::PersistentSet(Func pcmp)
        : cmp(pcmp),
        roots(std::vector<Nodeptr>()),
        nil(std::make_shared<Node>(T(), false, nullptr, nullptr))
    {
        roots.push_back(nil);
    }

    template<typename T, typename Func>
    template <typename ChildA, typename ChildB >
    typename  PersistentSet<T, Func>::Nodeptr
        PersistentSet<T, Func>::rotate(

            Nodeptr parent_of_x,
            Nodeptr x,
            ChildA childA,
            ChildB childB)
    {
        Nodeptr child_of_x = childB(x);
        childB(x) = childA(child_of_x);

        if (x == roots.back())
        {
            roots.pop_back();
            roots.push_back(child_of_x);
        }
        else if (x == childA(parent_of_x))
            childA(parent_of_x) = child_of_x;
        else
            childB(parent_of_x) = child_of_x;

        childA(child_of_x) = x;

        return child_of_x;
    }

    template <typename T, typename Func>
    template<typename TT>
    bool PersistentSet<T, Func>::generic_add(TT&& element)
    {

        std::deque<Nodeptr> path;
        auto newRoot = add_recursive( path,
                                      std::forward<TT>(element),
                                      roots.back() );

        bool added = newRoot != nullptr;
        if (added)
        {
            roots.push_back(newRoot);
            path.push_back(nil);
            balance_add(path);
        }
        return added;
    }

    template<typename T, typename Func>
    template<typename F, typename NF, typename TT>
    typename PersistentSet<T, Func>::Nodeptr
        PersistentSet<T, Func>::find_and_build(
            TT&& element,
            Nodeptr node,
            std::deque<Nodeptr> &path,
            F if_found,
            NF if_not_found)
    {
        if (node == nil)
            return if_not_found(element, path);

        bool is_less = cmp(element, node->key);
        bool is_equal = !is_less
                        && !cmp(node->key, element);

        if (is_equal)
            return if_found(node, path);

        auto direction = is_less ? left : right;
        auto child = find_and_build( std::forward<TT>(element),
                                     direction(node),
                                     path,
                                     if_found,
                                     if_not_found );
        
        if (child == nullptr) return child;

        auto copy = copy_node(node);
        path.push_back(copy);
        direction(copy) = child;

        return copy;
    }

    template<typename T, typename Func>
    template<typename TT>
    typename PersistentSet<T, Func>::Nodeptr
        PersistentSet<T, Func>::add_recursive(std::deque<Nodeptr>& path, TT &&element, Nodeptr & node)
    {

        auto if_not_found = [&](auto pelement, auto& path)
        {
            auto copy = create_node(std::forward<T>(pelement));
            path.push_back(copy);
            return copy;
        };
        auto if_found = [](auto node, auto& path) 
        { 
            return nullptr; 
        };
        return find_and_build(element, node, path, if_found, if_not_found);
    }

    template <typename T, typename Func>
    typename PersistentSet<T, Func>::Nodeptr
        PersistentSet<T, Func>::remove_recursive(const T& element, Nodeptr node, std::deque<Nodeptr>& path)
    {

        auto if_not_found = [](auto element, auto& path) 
        { 
            return nullptr; 
        };
        auto if_found = [&](auto pnode, auto& ppath)
        {
            auto copy = copy_node(pnode);
            ppath.push_back(copy);
            return copy;
        };
        return find_and_build(element, node, path, if_found, if_not_found);
    }

    template <typename T, typename Func>
    bool PersistentSet<T, Func>::add(const T& element)
    {
        return generic_add(const_cast<T&> (element));
    }

    template <typename T, typename Func>
    bool PersistentSet<T, Func>::add(T&& element)
    {
        return generic_add(std::move(element));
    }

    template<typename T, typename Func>
    typename PersistentSet<T, Func>::Nodeptr
        PersistentSet<T, Func>::copy_node(Nodeptr node) const
    {
        if (node == nil) return nil;
        return std::make_shared<Node>(node->key, node->isRed, node->left, node->right);
    }

    template <typename T, typename Func>
    template <typename TT>
    typename PersistentSet<T, Func>::Nodeptr
        PersistentSet<T, Func>::create_node(TT&& key)
    {
        return std::make_shared<Node>(std::forward<TT>(key), true, nil, nil);
    }

    template <typename T, typename Func>
    void PersistentSet<T, Func>::delete_node(std::deque<Nodeptr> & path)
    {

        auto removed = path.front();
        auto transplanted = removed->right;

        if (removed->left == nil)
        {
            path.pop_front();
            transplant(path.front(), removed, transplanted);
        }
        else if (removed->right == nil)
        {
            path.pop_front();
            transplanted = removed->left;
            transplant(path.front(), removed, transplanted);
        }
        else
        {
            auto temp = removed;
            removed->right = copy_node(removed->right);
            removed = build_min_path(removed->right, path);
            transplanted = removed->right;
            temp->key = std::move(removed->key);
            transplant(path.front(), removed, transplanted);
        }

        if (!removed->isRed)
            balance_remove(transplanted, path);

    }


    template <typename T, typename Func>
    typename PersistentSet<T, Func>::Nodeptr
        PersistentSet<T, Func>::build_min_path(Nodeptr node, std::deque<Nodeptr>& path)
    {
        while (node->left != nil)
        {
            node->left = copy_node(node->left);
            path.push_front(node);
            node = node->left;
        }
        return node;
    }

    template <typename T, typename Func>
    void PersistentSet<T, Func>::balance_remove(Nodeptr extra_black, std::deque<Nodeptr>& path)
    {

        auto parent = pop_front(path);
        while (extra_black != roots.back()
                  && !extra_black->isRed)
        {
            if (parent->left == extra_black)
                mirror_remove_balance(extra_black, parent, path, left, right);
            else
                mirror_remove_balance(extra_black, parent, path, right, left);
        }

        auto new_node = copy_node(extra_black);
        transplant(parent, extra_black, new_node);
        new_node->isRed = false;

    }
    template <typename T, typename Func>
    template <typename ChildA, typename ChildB >
    void PersistentSet<T, Func>::mirror_remove_balance(

        Nodeptr& extra_black,
        Nodeptr& parent,
        std::deque<Nodeptr> & path,
        ChildA childA,
        ChildB childB)
    {
        Nodeptr brother = childB(parent);
        if (brother->isRed)
        {
            brother = childB(parent) = copy_node(brother);

            std::swap(brother->isRed, parent->isRed);
            rotate(path.front(), parent, childA, childB);
            path.push_front(brother);
            brother = childB(parent);
        }
        if (!brother->left->isRed && !brother->right->isRed)
        {
            brother = childB(parent) = copy_node(brother);

            brother->isRed = true;
            extra_black = parent;
            parent = pop_front(path);
        }
        else
        {
            if (!childB(brother)->isRed)
            {
                brother = childB(parent) = copy_node(brother);

                childA(brother) = copy_node(childA(brother));
                std::swap(brother->isRed, childA(brother)->isRed);
                brother = rotate(parent, brother, childB, childA);
            }
            brother = childB(parent) = copy_node(brother);

            childB(brother) = copy_node(childB(brother));
            brother->isRed = parent->isRed;
            parent->isRed = false;
            childB(brother)->isRed = false;
            rotate(path.front(), parent, childA, childB);

            extra_black = roots.back();
            parent = nil;
        }

    }

    template <typename T, typename Func>
    bool PersistentSet<T, Func>::remove(const T& element)
    {
        std::deque<Nodeptr> path;

        auto node = remove_recursive( element,
                                      roots.back(),
                                      path );
        bool exist = node != nullptr;
        if (exist)
        {
            roots.push_back(node);
            path.push_back(nil);
            delete_node(path);
        }
        return exist;
    }


    template <typename T, typename Func>
    void PersistentSet<T, Func>::balance_add(std::deque<Nodeptr>& path)
    {
        auto no_compliant = pop_front(path);
        auto parent = pop_front(path);

        while (parent->isRed)
        {
            if (path.front()->left == parent)
                mirror_add_balance(parent, no_compliant, path, left, right);
            else
                mirror_add_balance(parent, no_compliant, path, right, left);
        }
        roots.back()->isRed = false;

    }

    template <typename T, typename Func>
    template <typename ChildA, typename ChildB >
    void PersistentSet<T, Func>::
        mirror_add_balance(

            Nodeptr &parent,
            Nodeptr &no_compliant,
            std::deque<Nodeptr>& path,
            ChildA childA,
            ChildB childB)
    {
        Nodeptr &uncle = childB(path.front());
        if (uncle->isRed)
        {
            uncle = copy_node(uncle);
            parent->isRed = false;
            uncle->isRed = false;
            path.front()->isRed = true;
            no_compliant = pop_front(path);
            parent = pop_front(path);
        }
        else
        {
            if (no_compliant == childB(parent))
            {
                std::swap(no_compliant, parent);
                rotate(path.front(), no_compliant, childA, childB);
            }
            auto grand_parent = pop_front(path);
            std::swap(grand_parent->isRed, parent->isRed);
            rotate(path.front(), grand_parent, childB, childA);
        }
    }

}

No comments:

Post a Comment