C++ Library Extensions 2022.12.09
To help learn modern C++ programming
045-subsets.cpp
Go to the documentation of this file.
1#include <tpf_output.hpp>
2#include <tpf_ncrnpr.hpp>
3
5auto endl = tpf::endl; // one carriage return and flush to console
6auto endL = tpf::endL; // two carriage returns and flush to console
7
8using element_t = size_t;
9using set_t = std::deque<element_t>;
10
11void build_subset(set_t S, set_t& R, // is the subset we are going to build
12 size_t r, size_t m_th)
13{
14 if(r==0)
15 return;
16 else if(S.size() == r) // S = {1, 2}, r = 2, then we append element of S to R
17 {
18 R.insert( R.end(),
19 std::make_move_iterator(S.begin()),
20 std::make_move_iterator(S.end()));
21
22 return;
23 }
24
25 // nCr = n-1 C r-1 + n-1 C r
26
27 auto n_1_c_r_1 = tpf::ncrnpr::ncr(S.size()-1, r-1);
28
29 if(m_th < n_1_c_r_1)
30 {
31 // for the first group
32
33 R.push_back(S.front()); // copy the first element of S to R
34 S.pop_front(); // remove the first element of S
35
36 --r; // Since we determined the first element of the subset R,
37 // we decrement r.
38
39 build_subset(S, R, r, m_th);
40 }
41 else
42 {
43 // for the second group
44
45 // we remove the first element of S
46 S.pop_front();
47
48 // but, we do not add the first element of S to R
49 m_th -= n_1_c_r_1;
50
51 build_subset(S, R, r, m_th);
52 }
53
54}
55
56void test_subsets(size_t n, size_t r)
57{
58 set_t S(n); // allocate memory for n elements
59
60 std::generate(S.begin(), S.end(),
61 [n = size_t{} ]() mutable{ return ++n; });
62
63 // std::iota(S.begin(), S.end(),
64 // [n = size_t{} ]() mutable{ return ++n; });
65
66 stream << "The set S : " << S << endL;
67
68 // total number of subsets
69 auto max_m_th = tpf::ncrnpr::ncr(n, r);
70
71 for(size_t m_th = 0; m_th < max_m_th; ++m_th)
72 {
73 set_t R;
74
75 build_subset(S, R, r, m_th);
76
77 stream << "m_th - > " << m_th << " : " << R << endl;
78 }
79
80}
81
82int main()
83{
84 test_subsets(4, 2);
85
86 stream << endL;
87
88 test_subsets(8, 4);
89
90}
auto endL
Definition: 045-subsets.cpp:6
void test_subsets(size_t n, size_t r)
Definition: 045-subsets.cpp:56
tpf::sstream stream
Definition: 045-subsets.cpp:4
auto endl
Definition: 045-subsets.cpp:5
void build_subset(set_t S, set_t &R, size_t r, size_t m_th)
Definition: 045-subsets.cpp:11
int main()
Definition: 045-subsets.cpp:82
std::deque< element_t > set_t
Definition: 061-subsets.cpp:9
enable_if_all_in_list_t< types::type_list_t< Type1, Type2 >, integral_list_t, ReturnType > ncr(Type1 nn, Type2 rr)
Definition: tpf_ncrnpr.hpp:390
constexpr auto endL
Definition: tpf_output.hpp:974
constexpr auto endl
Definition: tpf_output.hpp:973
Stream output operators << are implemented.