ATLAS Offline Software
Loading...
Searching...
No Matches
CombinationsGenerator.h
Go to the documentation of this file.
1/*
2 Copyright (C) 2002-2022 CERN for the benefit of the ATLAS collaboration
3*/
4
5#ifndef TRIG_HLTJETHYPO_COMBINATIONSGENERATOR_H
6#define TRIG_HLTJETHYPO_COMBINATIONSGENERATOR_H
7
8#include <algorithm>
9#include <string>
10#include <vector>
11#include <sstream>
12
13/*
14Combinations generator. Given n, k > 0, n>= k, bump() calculate sets
15a bit mask of length n with k set values and n-k unset values.
16
17get() uses the bitmask to return the postions of the k set values.
18
19When all combinations havebeen exhausted by succesive calls to bump
20the process cycles. At the point of recycling a bool flag is set.
21This flag is unset on the next call to bump().
22*/
23
25 public:
26
27 friend std::ostream& operator << (std::ostream&, const CombinationsGenerator&);
28
29 CombinationsGenerator(std::size_t n, std::size_t k):
30 m_invalid{false}, m_N{n}, m_K(k){
31
32 // if n==k, std::prev_permutations never returns false,
33 // so treat as a special case
34 if (m_N == 0 or m_K > m_N) {
35 m_invalid = true;
36 } else if (m_N==m_K) {
37 m_NequalsKvec.reserve(m_K);
38 for(std::size_t i = 0u; i != m_K; ++i){
39 m_NequalsKvec.push_back(i);
40 }
41 } else if (m_K < m_N){
42 m_bitmask = std::string(m_K, 1);
43 m_bitmask.resize(m_N, 0);
44 } else {
45 m_invalid = true;
46 }
47 }
48
49
50 std::vector<std::size_t> get() const {
51
52 if (m_K < m_N and m_K > 0) {
53 std::vector<std::size_t> comb;
54 for(std::size_t i = 0; i < m_bitmask.size(); ++i){
55 if(m_bitmask[i]){comb.push_back(i);}
56 }
57 return comb;
58 }
59
60 if(m_K == m_N) {return m_NequalsKvec;}
61
62 return std::vector<std::size_t>();
63 }
64
65 bool bump() {
66 // returns true if have cycled
67
68 if (m_K < m_N and m_K > 0) {
69 return ! std::prev_permutation(m_bitmask.begin(), m_bitmask.end());
70 }
71 return true;
72 }
73
74private:
75
77 std::string m_bitmask;
78
79 std::size_t m_N;
80 std::size_t m_K;
81 std::vector<std::size_t> m_NequalsKvec;
82};
83
84std::ostream& operator << (std::ostream& os, const CombinationsGenerator& cg);
85
86#endif
std::ostream & operator<<(std::ostream &os, const CombinationsGenerator &cg)
generate all possible combinations of objects
friend std::ostream & operator<<(std::ostream &, const CombinationsGenerator &)
CombinationsGenerator(std::size_t n, std::size_t k)
std::vector< std::size_t > get() const
std::vector< std::size_t > m_NequalsKvec