C++ Library Extensions 2022.12.09
To help learn modern C++ programming
046-permutations.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 output
6auto endL = tpf::endL; // two carriage return and flush to console output
7
8using element_t = size_t;
9using set_t = std::vector<element_t>;
10
11void build_permutation(set_t S, set_t& R, size_t r, size_t m_th)
12{
13 if(r == 0 || S.empty())
14 return;
15
16 auto n = S.size(); // n = 4, r = 3
17
18 auto n_1_p_r_1 = tpf::ncrnpr::npr(n-1, r-1); // 3P2 = 6
19
20 auto quotient = m_th / n_1_p_r_1; // index of S
21 // == 1 = (7 / 6)
22
23 R.push_back ( S[quotient] ); // insert quotient-th element of S to R
24
25 // 0, 1, 2, 3 <- quotient
26 // S = {1, 2, 3, 4}, S' = { 1, 3, 4}
27 S.erase(S.begin() + quotient); // remove S[quotient] from S
28
29 m_th %= n_1_p_r_1; // m_th = m_th % n_1_p_r_1, 7 %= 6
30 // m_th = 1
31
32 build_permutation(S, R, r-1, m_th);
33}
34
35void test_permutations(size_t n, size_t r)
36{
37 set_t S(n); // allocate memory for n elements
38 std::iota(S.begin(), S.end(), 1);
39
40 stream << " The set S : " << S << endL;
41
42 auto max_m_th = tpf::ncrnpr::npr(n, r);
43
44 for(size_t m_th = 0; m_th < max_m_th; ++m_th)
45 {
46 set_t R; // permutation
47
48 build_permutation(S, R, r, m_th);
49
50 stream << " m_th -> " << std::setw(3) << m_th << " : "
51 << R << endl;
52 }
53
54}
55
56int main()
57{
59
60 stream << endL;
61
63
64 stream << endL;
65
67
68 stream << endL;
69
71
72 stream << endL;
73
75
76
77}
auto endL
void build_permutation(set_t S, set_t &R, size_t r, size_t m_th)
tpf::sstream stream
auto endl
void test_permutations(size_t n, size_t r)
int main()
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 > npr(Type1 nn, Type2 rr)
Definition: tpf_ncrnpr.hpp:428
constexpr auto endL
Definition: tpf_output.hpp:974
constexpr auto endl
Definition: tpf_output.hpp:973
Stream output operators << are implemented.