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