C++ Library Extensions 2022.12.09
To help learn modern C++ programming
055-functional_programming.cpp
Go to the documentation of this file.
1#include <iostream>
2
3/*
4 In functional programming paradigm,
5
6 1. The state of data is immutable.
7
8 n C r = n-1 C r-1 + n-1 C r
9 */
10
11template<size_t N, size_t R>
12struct nCr
13{
14 constexpr static size_t value = nCr< N-1, R-1 >::value + nCr< N-1, R>::value;
15};
16
17template<size_t N>
18struct nCr<N, N>
19{
20 constexpr static size_t value = 1;
21};
22
23template<size_t N>
24struct nCr<N, 0>
25{
26 constexpr static size_t value = 1;
27};
28
29template<size_t N>
30struct nCr<N, 1>
31{
32 constexpr static size_t value = N;
33};
34
35template<size_t N, size_t R>
36constexpr size_t combinations = nCr<N, R>::value;
37
38template<size_t Start_R, size_t End_R>
40{
41 template<size_t N>
42 static void print_combinations()
43 {
44 if constexpr(Start_R <= End_R)
45 {
46 std::cout << N << " C " << Start_R << " = "
47 << combinations<N, Start_R> << std::endl;
48 }
49
50 if constexpr(Start_R + 1 <= End_R)
51 {
52 static_loop<Start_R+1, End_R>:: template print_combinations<N>();
53 }
54 }
55};
56
57template<size_t N>
59{
60 static_loop<0, N>:: template print_combinations<N>();
61}
62
63int main()
64{
65 test_combinations<5>();
66}
auto & cout
void test_combinations()
constexpr size_t combinations
auto & endl
static constexpr size_t value
static void print_combinations()