Way more inefficient version of pingala with better padding.

This commit is contained in:
2025-03-29 22:05:59 +00:00
parent c1355e3003
commit 8dbedb691d

View File

@@ -4,38 +4,39 @@
*/ */
#include <cstdio> #include <cstdio>
#include <iostream>
#include <sstream>
#include <string> #include <string>
#include <vector> #include <vector>
void padding(size_t n, size_t depth) std::vector<std::string> generate_triangle(const size_t depth)
{
for (size_t i = 0; i < ((depth - n) / 2); ++i)
printf("\t");
}
void generate_triangle(const size_t depth)
{ {
std::vector<std::string> levels;
std::vector<size_t> items; std::vector<size_t> items;
std::stringstream ss;
levels.reserve(depth);
items.reserve(depth * depth); items.reserve(depth * depth);
#define AT(i, j) items[((i) * depth) + (j)] #define AT(i, j) items[((i) * depth) + (j)]
AT(0, 0) = 1; AT(0, 0) = 1;
padding(0, depth); levels.push_back("1");
printf("%lu\n", items[0]);
for (size_t i = 1; i < depth; ++i) for (size_t i = 1; i < depth; ++i)
{ {
AT(i, 0) = 1; AT(i, 0) = 1;
padding(i, depth); ss << "1 ";
printf("%lu,\t", AT(i, 0));
for (size_t j = 1; j < i; ++j) for (size_t j = 1; j < i; ++j)
{ {
// Recurrence relation
AT(i, j) = AT(i - 1, j - 1) + AT(i - 1, j); AT(i, j) = AT(i - 1, j - 1) + AT(i - 1, j);
printf("%lu,\t", AT(i, j)); ss << AT(i, j) << " ";
} }
AT(i, i) = 1; AT(i, i) = 1;
printf("%lu\n", AT(i, i)); ss << "1";
levels.push_back(ss.str());
ss.str(std::string{});
} }
#undef AT #undef AT
return levels;
} }
void usage(FILE *fp) void usage(FILE *fp)
@@ -46,18 +47,28 @@ void usage(FILE *fp)
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
if (argc < 2) // Variable declarations
{ std::vector<std::string> levels;
usage(stderr); int depth = 0;
return 1;
}
int arg = std::stoi(argv[1]);
if (arg <= 0)
{
usage(stderr);
return 1;
}
generate_triangle(arg); if (argc < 2)
goto error;
depth = std::stoi(argv[1]);
if (depth <= 0)
goto error;
levels = generate_triangle(depth);
for (const auto &level : levels)
{
for (size_t i = 0;
i < (levels[levels.size() - 1].size() - level.size()) / 2; ++i)
{
printf(" ");
}
printf("%s\n", level.c_str());
}
return 0; return 0;
error:
usage(stderr);
return 1;
} }