C++ Mathematical Expression Toolkit (ExprTk) release
Loading...
Searching...
No Matches
exprtk_pascals_triangle.cpp
Go to the documentation of this file.
1/*
2 **************************************************************
3 * C++ Mathematical Expression Toolkit Library *
4 * *
5 * ExprTk Pascal's Triangle *
6 * Author: Arash Partow (1999-2024) *
7 * URL: https://www.partow.net/programming/exprtk/index.html *
8 * *
9 * Copyright notice: *
10 * Free use of the Mathematical Expression Toolkit Library is *
11 * permitted under the guidelines and in accordance with the *
12 * most current version of the MIT License. *
13 * https://www.opensource.org/licenses/MIT *
14 * SPDX-License-Identifier: MIT *
15 * *
16 **************************************************************
17*/
18
19
20#include <cstdio>
21#include <string>
22
23#include "exprtk.hpp"
24
25
26template <typename T>
28{
29 typedef exprtk::symbol_table<T> symbol_table_t;
30 typedef exprtk::expression<T> expression_t;
31 typedef exprtk::parser<T> parser_t;
32 typedef exprtk::function_compositor<T> compositor_t;
33 typedef typename compositor_t::function function_t;
34
36
37 symbol_table_t symbol_table;
38 symbol_table.add_package(io_package);
39 symbol_table.add_function("print_coeff",
40 [](T t)
41 {
42 printf("%6d", static_cast<unsigned int>(t));
43 return T(0);
44 });
45
46 compositor_t compositor(symbol_table);
47
48 compositor.add(
49 function_t("n_choose_k")
50 .vars("n","k")
51 .expression
52 (
53 " switch "
54 " { "
55 " case n <= k : 1; "
56 " case k <= 0 : 1; "
57 " default : n_choose_k(n - 1, k - 1) + "
58 " n_choose_k(n - 1, k ) ; "
59 " } "
60 ));
61
62 const std::string pascals_triangle_program =
63 " const var rows := 20; "
64 " "
65 " for (var n := 0; n < rows; n += 1) "
66 " { "
67 " for (var s := 0; s <= (rows - n) - 2; s += 1) "
68 " { "
69 " print(' '); "
70 " }; "
71 " "
72 " for (var k := 0; k <= n; k += 1) "
73 " { "
74 " print_coeff(n_choose_k(n,k)); "
75 " }; "
76 " "
77 " println(''); "
78 " } ";
79
80 expression_t expression;
81 expression.register_symbol_table(symbol_table);
82
83 parser_t parser;
84 parser.compile(pascals_triangle_program,expression);
85
86 expression.value();
87}
88
89int main()
90{
91 pascals_triangle<double>();
92 return 0;
93}
void pascals_triangle()