c++ - 不使用 for/while 循环的 Pascal 三角形计算

标签 c++ templates recursion variadic-templates pascals-triangle

我想从给定的数据集生成 Pascal 金字塔数据,如下所示

金字塔(1,2,3,4,5,6,7,8,9);

这就是我一直在做的,但它只到达第二层,而我希望它递归循环到顶部。

template<typename T>
const T Pyramid(T a, T b)
{   
    return a + b;
}

template<typename T, typename ...A>
const T Pyramid(T t1, T t2, A...a)
{

    return Pyramid(t1, t2) + Pyramid(t2, a...);
}

你能帮我填满下一层吗? ;)

最佳答案

C++17

这是 C++17 的解决方案(使用 fold expressions ):

#include <iostream>
#include <stdexcept>
#include <utility>


using Integer = std::uint64_t;


constexpr auto Factorial(const Integer n)
{
    Integer factorial = 1;

    for (Integer i = 2; i <= n; ++i)
    {
        factorial *= i;
    }

    return factorial;
}

constexpr auto Binom(const Integer n, const Integer m)
{
    if (n < m)
    {
        throw std::invalid_argument("Binom: n should not be less than m");
    }

    return Factorial(n) / Factorial(m) / Factorial(n - m);
}

template <Integer... indices, typename... Types>
constexpr auto PyramidImplementation(std::integer_sequence<Integer, indices...>, Types... values)
{    
    return ((Binom(sizeof...(values), indices) * values) + ...);
}

template <typename... Types>
constexpr auto Pyramid(Types... values)
{
    return PyramidImplementation(std::make_integer_sequence<Integer, sizeof...(values)>{}, values...);
}

// ...

constexpr auto pyramid = Pyramid(1, 2, 3, 4, 5, 6, 7, 8, 9);

std::cout << "Pyramid = " << pyramid << std::endl;

Live demo

此解决方案不使用递归,因为 a[i] (i = 0 ... n - 1) 所需的结果可以计算为binom(n, i) * a[i] 的总和(对于 i = 0 ... n - 1),其中 binom(n, m )binomial coefficient . Binom 函数以最简单的方式实现,因此它仅适用于较小的 n 值。

C++14

可以通过以下 PyramidImplementation 函数实现使代码与 C++14 兼容:

#include <type_traits>


template <Integer... indices, typename... Types>
constexpr auto PyramidImplementation(std::integer_sequence<Integer, indices...>, Types... values)
{
    using Do = int[];
    std::common_type_t<Types...> pyramid{};

    (void)Do{0, (pyramid += Binom(sizeof...(values), indices) * values, 0)...};

    return pyramid;
}

Live demo

关于c++ - 不使用 for/while 循环的 Pascal 三角形计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47575803/

相关文章:

python - Raspbian-Windows openCV 视频流之间的套接字

c++ - 在 C++ 中,为什么我不能使用两个默认的随机引擎生成独立的随机整数样本

c++ - 为什么这个包装分配器的构造函数在模板替换期间采用了错误的类型(完美转发构造函数)?

c++ - 查找最近的点对 - 如何在递归端对函数调用中实现拆分对

c++ - Multimap 使用 std::make_pair 与 std::pair 构造函数插入键类型信息

c++ - 如何输出一个字符**

javascript - Jade 包含基于变量的模板

c++ - 我可以避免在一系列函数调用中使用模板消歧器吗?

Java递归向前和向后输出名称

algorithm - 我怎样才能找到递归关系?