Wednesday, June 15, 2022

Pascal Triangle 3/100

 Pascal Triangle 3/100

Running out of screen space!


Day 3 of 100 Days of Code

So, Leetcode has this problem of creating Pascal triangle. And I've seen the solutions that people put up. It's vector this, list that, and I think doing it that way is overkill. What's with push-pop and all that jazz.


Personally, I think a single dimensional array suffice. After all, you're not computing beyond the last line, and that you can compute in either direction. Every solution I saw was from 0-N, whereas I do N-0, and save myself an extra array!


Computing the values is one thing. Displaying it is another, and I found out real quick that I don't have a big enough monitor to display more that 20 lines of values without losing the shape of the triangle. By the way, I redid the algorithm for displaying the triangle, so no more recursion being used from Day 1 program.


#include <stdio.h>
#include <stdlib.h> 
int PascalTri(int N) {
  int rows[100]; int i,j; 
  if (N<0 || N>20) return 1; //Out of bounds!
  rows[0]=1; for (i=99;i;i--) rows[i]=0;
  for (i=0;i<N;i++) {
    for (j=N-i-1;j;j--) printf("   ");
    for (j=0;j<=i;j++) printf(" %5d",rows[j]);
    puts("");
    for (j=i+1;j;j--) rows[j]+=rows[j-1];
  }
  return 0;
} 
int main (int argc, char *argv[] ) {
  int e=0;
  if   (argc<2) puts("Usage: pascaltri N\n");
  else e=PascalTri(atoi(argv[1]));
  if (e==1) puts("Error: Range is 0-20 inclusive.");
  return e;
}



One final note: Turns out that there is a way to mathematically compute the values so that I don't even need the array. Alas, I'm no mathematician.


No comments:

Post a Comment