Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Pascal's triangle

Name: Anonymous 2012-01-05 17:41

Motivated by the Hacker News challenge in http://news.ycombinator.com/item?id=3429466 I just made this.


#include <stdio.h>
#include <stdlib.h>

int64_t* next_pascal_row(int64_t* previous_row, int64_t previous_size)
{
  int64_t* retval = (int64_t*)malloc(sizeof(int64_t)*(previous_size+2));
  int64_t i;
  for (i=0;i<previous_size+1;i++) {
    if (i==0 || i == previous_size) {
      retval[i] = 1;
    } else {
      retval[i] = previous_row[i-1] + previous_row[i];
    }
  }
  return retval;
}

void print_row(int64_t* row, int64_t size)
{
  int64_t i;
  for(i = 0; i < size; i++) {
    printf("%lld ",row[i]);
  }
  printf("\n");
}

int main()
{
  int64_t* first_row = (int64_t*)malloc(sizeof(int64_t));
  int64_t* previous_row;
  int64_t* next_row;
  int64_t i,size;
  first_row[0] = 1;
  size = 1;
  print_row(first_row,size);
  previous_row = first_row;
  for(i = 0; i<30;i++) {
    next_row = next_pascal_row(previous_row,size);
    size++;
    print_row(next_row,size);
    free(previous_row);
    previous_row = next_row;
  }
  free(next_row);
}

Opinions? Yeah, int64_t is probably a GNU extension, I don't care as long as it works with gcc. U mad? Also, post you're own solutions. If you can't do the Pascal, you can just go ahead and apply to your're nearest McDonald's, because you ain't worth shit.

Name: Anonymous 2012-01-05 22:44

>>28
Square array = wasted memory. Also, using stack space is bad.
>>37
Using stack space is bad.
>>1
Multiple mallocs = slow.

And I present to you... the best pascal.c in this thread. Only uses enough memory to hold all the numbers. It's also the fastest-running program.

#include <stdio.h>
#include <stdlib.h>
#define NTH_IN_ROW(r, n) (((r) * (r) + (r)) / 2 + (n))
int main() {
        long *a, i, j, r;
        scanf("%ld", &r);
        a = malloc(sizeof(long) * ((r + 1) * (r + 1) + r + 1) / 2);
        for (i = 0; i <= r; i++) {
                a[NTH_IN_ROW(i, 0)] = 1;
                a[NTH_IN_ROW(i, i)] = 1;
                if (i > 1)
                        for (j = 1; j < i; j++)
                                a[NTH_IN_ROW(i, j)] =
                                        a[NTH_IN_ROW(i - 1, j)] +
                                        a[NTH_IN_ROW(i - 1, j - 1)];
        }
        for (j = 0; j <= r; j++)
                printf("%ld ", a[NTH_IN_ROW(r, j)]);
        putchar('\n');
        return 0;
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List