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