Integer_combination_iterator.h
1 /* This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
2  * See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
3  * Author(s): Siargey Kachanovich
4  *
5  * Copyright (C) 2019 Inria
6  *
7  * Modification(s):
8  * - YYYY/MM Author: Description of the modification
9  */
10 
11 #ifndef PERMUTAHEDRAL_REPRESENTATION_INTEGER_COMBINATION_ITERATOR_H_
12 #define PERMUTAHEDRAL_REPRESENTATION_INTEGER_COMBINATION_ITERATOR_H_
13 
14 #include <vector>
15 #include <boost/range/iterator_range.hpp>
16 
17 namespace Gudhi {
18 
19 namespace coxeter_triangulation {
20 
21 typedef unsigned uint;
22 
28  : public boost::iterator_facade<Integer_combination_iterator, std::vector<uint> const,
29  boost::forward_traversal_tag> {
30  using value_t = std::vector<uint>;
31 
32  private:
33  friend class boost::iterator_core_access;
34 
35  bool equal(Integer_combination_iterator const& other) const { return (is_end_ && other.is_end_); }
36 
37  value_t const& dereference() const { return value_; }
38 
39  void increment() {
40  uint j1 = 0;
41  uint s = 0;
42  while (value_[j1] == 0 && j1 < k_) j1++;
43  uint j2 = j1 + 1;
44  while (value_[j2] == bounds_[j2]) {
45  if (bounds_[j2] != 0) {
46  s += value_[j1];
47  value_[j1] = 0;
48  j1 = j2;
49  }
50  j2++;
51  }
52  if (j2 >= k_) {
53  is_end_ = true;
54  return;
55  }
56  s += value_[j1] - 1;
57  value_[j1] = 0;
58  value_[j2]++;
59  uint i = 0;
60  while (s >= bounds_[i]) {
61  value_[i] = bounds_[i];
62  s -= bounds_[i];
63  i++;
64  }
65  value_[i++] = s;
66  }
67 
68  public:
69  template <class Bound_range>
70  Integer_combination_iterator(const uint& n, const uint& k, const Bound_range& bounds)
71  : value_(k + 2), is_end_(n == 0 || k == 0), k_(k) {
72  bounds_.reserve(k + 2);
73  uint sum_radices = 0;
74  for (auto b : bounds) {
75  bounds_.push_back(b);
76  sum_radices += b;
77  }
78  bounds_.push_back(2);
79  bounds_.push_back(1);
80  if (n > sum_radices) {
81  is_end_ = true;
82  return;
83  }
84  uint i = 0;
85  uint s = n;
86  while (s >= bounds_[i]) {
87  value_[i] = bounds_[i];
88  s -= bounds_[i];
89  i++;
90  }
91  value_[i++] = s;
92 
93  while (i < k_) value_[i++] = 0;
94  value_[k] = 1;
95  value_[k + 1] = 0;
96  }
97 
98  // Used for the creating an end iterator
99  Integer_combination_iterator() : is_end_(true), k_(0) {}
100 
101  private:
102  value_t value_; // the dereference value
103  bool is_end_; // is true when the current integer combination is the final one
104 
105  uint k_;
106  std::vector<uint> bounds_;
107 };
108 
109 } // namespace coxeter_triangulation
110 
111 } // namespace Gudhi
112 
113 #endif
Class that allows the user to generate combinations of k elements in a set of n elements....
Definition: Integer_combination_iterator.h:29
Gudhi namespace.
Definition: SimplicialComplexForAlpha.h:14