OpenSDN source code
subset.h
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
3  * Copyright Contributors to the OpenSDN project
4  */
5 
6 #ifndef ctrlplane_subset_h
7 #define ctrlplane_subset_h
8 
9 #include <cassert>
10 #include <vector>
11 
12 // Generates all the possible subset permutations of a particular set.
13 template <typename Container>
15 public:
16  SubsetGenerator(const Container &container)
17  : container_(container) {
18  stack_.push_back(0);
19  }
20 
21  bool HasNext() const {
22  if (container_.size() <= 1) {
23  return false;
24  }
25  return (stack_.front() < 1);
26  }
27 
28  // generate the next permutation.
29  // rhs is the complement of lhs in container.
30  void Next(Container *lhs, Container *rhs) {
31  lhs->clear();
32  rhs->clear();
33 
34  int prev = 0;
35  for (unsigned int i = 0; i < stack_.size(); i++) {
36  int index = stack_[i];
37  assert((std::size_t)index < container_.size());
38 
39  for (int n = prev; n < index; n++) {
40  rhs->push_back(container_[n]);
41  }
42 
43  lhs->push_back(container_[index]);
44  prev = index + 1;
45  }
46  for (unsigned int n = prev; n < container_.size(); n++) {
47  rhs->push_back(container_[n]);
48  }
49  int last = stack_.back();
50  if (stack_.size() < container_.size() - 1) {
51  last++;
52  if ((std::size_t) last < container_.size()) {
53  stack_.push_back(last);
54  return;
55  }
56  }
57  while (true) {
58  stack_.back() += 1;
59  if ((std::size_t) stack_.back() < container_.size()) {
60  break;
61  }
62  if (stack_.size() == 1) {
63  break;
64  }
65  stack_.pop_back();
66  }
67  }
68 
69 private:
70  const Container &container_;
71  std::vector<int> stack_;
72 };
73 
74 #endif
bool HasNext() const
Definition: subset.h:21
SubsetGenerator(const Container &container)
Definition: subset.h:16
const Container & container_
Definition: subset.h:70
std::vector< int > stack_
Definition: subset.h:71
void Next(Container *lhs, Container *rhs)
Definition: subset.h:30