aboutsummaryrefslogtreecommitdiff
path: root/impls/pingala.cpp
diff options
context:
space:
mode:
authorAryadev Chavali <aryadev@aryadevchavali.com>2025-03-29 22:05:59 +0000
committerAryadev Chavali <aryadev@aryadevchavali.com>2025-03-29 22:05:59 +0000
commit8dbedb691dd091a1c6bb6453aeb360e0227a7044 (patch)
tree556ab303a490d5ccc238b57ff07243b2ca096ebd /impls/pingala.cpp
parentc1355e3003a079d4006c63fbddf055e05300c250 (diff)
downloadalgorithms-8dbedb691dd091a1c6bb6453aeb360e0227a7044.tar.gz
algorithms-8dbedb691dd091a1c6bb6453aeb360e0227a7044.tar.bz2
algorithms-8dbedb691dd091a1c6bb6453aeb360e0227a7044.zip
Way more inefficient version of pingala with better padding.
Diffstat (limited to 'impls/pingala.cpp')
-rw-r--r--impls/pingala.cpp59
1 files changed, 35 insertions, 24 deletions
diff --git a/impls/pingala.cpp b/impls/pingala.cpp
index 510aa50..97d3017 100644
--- a/impls/pingala.cpp
+++ b/impls/pingala.cpp
@@ -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[])
{
+ // Variable declarations
+ std::vector<std::string> levels;
+ int depth = 0;
+
if (argc < 2)
+ goto error;
+ depth = std::stoi(argv[1]);
+ if (depth <= 0)
+ goto error;
+
+ levels = generate_triangle(depth);
+ for (const auto &level : levels)
{
- usage(stderr);
- return 1;
- }
- int arg = std::stoi(argv[1]);
- if (arg <= 0)
- {
- usage(stderr);
- return 1;
+ for (size_t i = 0;
+ i < (levels[levels.size() - 1].size() - level.size()) / 2; ++i)
+ {
+ printf(" ");
+ }
+ printf("%s\n", level.c_str());
}
-
- generate_triangle(arg);
return 0;
+error:
+ usage(stderr);
+ return 1;
}