Triangle numbers implementation
This commit is contained in:
8
Makefile
8
Makefile
@@ -1,6 +1,10 @@
|
||||
CC=clang
|
||||
CC=g++
|
||||
CFLAGS=-pedantic -Wall -Wextra -fsanitize=address -fsanitize=undefined -ggdb -fsanitize=address
|
||||
OUT=
|
||||
ARGS=
|
||||
|
||||
pingala.out: impls/pingala.cpp
|
||||
$(CC) $(CFLAGS) $^ -o $@
|
||||
|
||||
btree.out: impls/btree.cpp
|
||||
$(CC) $(CFLAGS) $^ -o $@
|
||||
@@ -16,7 +20,7 @@ vec.out: impls/vec.c
|
||||
|
||||
.PHONY: run
|
||||
run: $(OUT)
|
||||
./$^
|
||||
./$^ $(ARGS)
|
||||
|
||||
.PHONY: clean
|
||||
clean:
|
||||
|
||||
63
impls/pingala.cpp
Normal file
63
impls/pingala.cpp
Normal file
@@ -0,0 +1,63 @@
|
||||
/* pingala.cpp
|
||||
* Created: 2024-09-15
|
||||
* Author: Aryadev Chavali
|
||||
*/
|
||||
|
||||
#include <cstdio>
|
||||
#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<size_t> items;
|
||||
items.reserve(depth * depth);
|
||||
#define AT(i, j) items[((i) * depth) + (j)]
|
||||
AT(0, 0) = 1;
|
||||
padding(0, depth);
|
||||
printf("%lu\n", items[0]);
|
||||
for (size_t i = 1; i < depth; ++i)
|
||||
{
|
||||
AT(i, 0) = 1;
|
||||
padding(i, depth);
|
||||
printf("%lu,\t", AT(i, 0));
|
||||
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));
|
||||
}
|
||||
AT(i, i) = 1;
|
||||
printf("%lu\n", AT(i, i));
|
||||
}
|
||||
#undef AT
|
||||
}
|
||||
|
||||
void usage(FILE *fp)
|
||||
{
|
||||
fprintf(fp, "Usage: pingala.out [depth]\n"
|
||||
"\tdepth: Depth of triangle generated\n");
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
generate_triangle(arg);
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user