C++ Library Extensions 2022.12.09
To help learn modern C++ programming
061-subsets.cpp
Go to the documentation of this file.
1#include <tpf_output.hpp>
2#include <tpf_ncrnpr.hpp>
3
7
8using element_t = size_t;
9using set_t = std::deque<element_t>;
10using sets_t = std::deque<set_t>;
11
12void build_subset(set_t& R, set_t S, size_t r, size_t m_th)
13{
14 auto n = S.size();
15
16 if(r == 0)
17 return;
18 else if(n == r)
19 {
20 R.insert(R.end(),
21 std::make_move_iterator(S.begin()),
22 std::make_move_iterator(S.end()));
23
24 return;
25 }
26
27 auto n_1_C_r_1 = tpf::ncrnpr::ncr(n-1, r-1);
28
29 if(m_th < n_1_C_r_1 )
30 {
31 R.push_back(S.front()); // copy the first element of the set S
32 // to the end of the set R
33
34 S.pop_front(); // remove the first element of the set S
35
36 --r; // We have chosen one element,
37 // so, decrement r
38
39 build_subset(R, S, r, m_th);
40 }
41 else
42 {
43 S.pop_front();
44
45 m_th -= n_1_C_r_1;
46
47 build_subset(R, S, r, m_th);
48 }
49}
50
51void test_build_subset(size_t n, size_t r)
52{
53 set_t S(n);
54
55 std::iota(S.begin(), S.end(), 1);
56
57 stream <<"The set S: " << S << endL;
58
59 auto ncr = tpf::ncrnpr::ncr(n, r);
60
61 for(size_t m_th = 0; m_th < ncr; ++m_th)
62 {
63 set_t R;
64 build_subset(R, S, r, m_th);
65
66 stream << "m_th -> "<< m_th <<" : " << R << endl;
67 }
68}
69
70int main()
71{
72 // from a set S = { 1, 2, 3, 4}
73 // we choose 2 elements and make subsets
75
76 stream << endL;
77
78 // from a set S = {1, 2, 3, 4, 5}
79 // we choose 2 elements and make subsets
81
82 return 0;
83}
auto endL
Definition: 061-subsets.cpp:6
std::deque< element_t > set_t
Definition: 061-subsets.cpp:9
tpf::sstream stream
Definition: 061-subsets.cpp:4
std::deque< set_t > sets_t
Definition: 061-subsets.cpp:10
void build_subset(set_t &R, set_t S, size_t r, size_t m_th)
Definition: 061-subsets.cpp:12
void test_build_subset(size_t n, size_t r)
Definition: 061-subsets.cpp:51
auto endl
Definition: 061-subsets.cpp:5
int main()
Definition: 061-subsets.cpp:70
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.