aboutsummaryrefslogtreecommitdiff
path: root/impls/pingala.cpp
blob: dc14f60f8b239bc3afe3f84d11f21cac066b1970 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/* pingala.cpp
 * Created: 2024-09-15
 * Author: Aryadev Chavali
 */

#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

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.resize(depth * depth);

#define AT(i, j) items[((i) * depth) + (j)]
  AT(0, 0) = 1;
  levels.push_back("1");
  for (size_t i = 1; i < depth; ++i)
  {
    AT(i, 0) = 1;
    ss << "1 ";
    for (size_t j = 1; j < i; ++j)
    {
      AT(i, j) = AT(i - 1, j - 1) + AT(i - 1, j);
      ss << AT(i, j) << " ";
    }
    AT(i, i) = 1;
    ss << "1";
    levels.push_back(ss.str());
    ss.str(std::string{});
  }
#undef AT

  return levels;
}

void usage(FILE *fp)
{
  fprintf(fp, "Usage: pingala.out [depth]\n"
              "\tdepth: Depth of triangle generated\n");
}

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)
  {
    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;
}