CMR  1.3.0
combinations.hpp
Go to the documentation of this file.
1 #pragma once
2 
3 #include <vector>
4 
5 namespace tu
6 {
7 
12  class last_combination_exception: std::exception
13  {
14  public:
16  {
17 
18  }
19 
20  virtual ~last_combination_exception() throw ()
21  {
22 
23  }
24 
25  virtual const char* what() const throw ()
26  {
27  return "Already last combination";
28  }
29  };
30 
32  {
33  protected:
34  std::vector <size_t> _data;
35  size_t _size;
36 
37  public:
39 
40  combination(size_t n, size_t k) :
41  _data(k), _size(n)
42  {
43  assert(k <= n);
44  for (size_t i = 0; i < k; ++i)
45  {
46  _data[i] = i;
47  }
48  }
49 
51 
52  size_t operator[](size_t index) const
53  {
54  return _data[index];
55  }
56 
57  size_t n() const
58  {
59  return _size;
60  }
61 
62  size_t k() const
63  {
64  return _data.size();
65  }
66 
72  bool is_last() const
73  {
74  return _data.empty() || _data[0] == _size - _data.size();
75  }
76 
79 
80  void next()
81  {
82  if (is_last())
84 
85  // Find end of first consecutive block.
86  size_t last_consecutive_one = 0;
87  while (last_consecutive_one + 1 < _data.size())
88  {
89  if (_data[last_consecutive_one + 1] != _data[last_consecutive_one] + 1)
90  break;
91  last_consecutive_one++;
92  }
93 
94  // Move end one entry further.
95  _data[last_consecutive_one]++;
96 
97  // Move all others of block to beginning.
98  for (size_t i = 0; i < last_consecutive_one; ++i)
99  {
100  _data[i] = i;
101  }
102  }
103  };
104 
113  inline std::ostream& operator<<(std::ostream& stream, const combination& c)
114  {
115  size_t next = (c.k() > 0 && c[0] == 0) ? 1 : 0;
116  stream << next;
117 
118  for (size_t i = 1; i < c.n(); ++i)
119  {
120  if ((next < c.k()) && c[next] == i)
121  {
122  stream << " 1";
123  next++;
124  }
125  else
126  {
127  stream << " 0";
128  }
129  }
130  return stream;
131  }
132 
133 } /* namespace tu */
Definition: combinations.hpp:32
combination(size_t n, size_t k)
Init with (1, ..., 1, 0, ..., 0)
Definition: combinations.hpp:40
std::vector< size_t > _data
Definition: combinations.hpp:34
bool is_last() const
Definition: combinations.hpp:72
size_t operator[](size_t index) const
Where is the index's 1 entry?
Definition: combinations.hpp:52
size_t n() const
Definition: combinations.hpp:57
size_t _size
Definition: combinations.hpp:35
void next()
Definition: combinations.hpp:80
size_t k() const
Definition: combinations.hpp:62
Definition: combinations.hpp:13
last_combination_exception()
Definition: combinations.hpp:15
virtual ~last_combination_exception()
Definition: combinations.hpp:20
virtual const char * what() const
Definition: combinations.hpp:25
Definition: algorithm.hpp:14
std::ostream & operator<<(std::ostream &stream, const binary_linear_space &space)
Definition: binary_linear_space.hpp:205