News for hackers. Stuff that matters.
Re:Why 37signals Doesn't Hire Programmers Based on Brainteasers by nitrogen on Thursday January 05, 2012 @11:39PM (#3431988)
What I would find really fascinating is if someone could explain to me why programmers have the urge to solve a programming interview problem whenever one is posted.

Not that anyone will ever read this... I thought I'd managed to escape this time, but then I thought it might be some good practice, so I timed myself...

  nitrogen@n2:~ $ time bash
  nitrogen@n2:~ $ vim /tmp/pascal.c
  nitrogen@n2:~ $ cd /tmp
  nitrogen@n2:/tmp $ gcc -std=c99 -Wall -Wextra pascal.c -o pascal
  pascal.c: In function ‘main’:
  pascal.c:15:21: error: expected ‘;’ before ‘)’ token
  pascal.c:15:21: error: expected statement before ‘)’ token
  pascal.c:16:2: error: too few arguments to function ‘calloc’
  nitrogen@n2:/tmp $ vim pascal.c
  nitrogen@n2:/tmp $ vim pascal.c
  nitrogen@n2:/tmp $ ./pas^C
  nitrogen@n2:/tmp $ gcc -std=c99 -Wall -Wextra pascal.c -o pascal
  nitrogen@n2:/tmp $ ./pascal 1
  1 
  nitrogen@n2:/tmp $ ./pascal 2
  1 1 
  nitrogen@n2:/tmp $ ./pascal 3
  1 2 1 
  nitrogen@n2:/tmp $ ./pascal 4
  1 3 3 1 
  nitrogen@n2:/tmp $ ./pascal 5
  1 4 6 4 1 
  nitrogen@n2:/tmp $ ./pascal 6
  1 5 10 10 5 1 
  nitrogen@n2:/tmp $ ./pascal 7
  1 6 15 20 15 6 1 
  nitrogen@n2:/tmp $ exit
  exit
  
  real	4m5.621s
  user	0m0.928s
  sys	0m0.136s
The initial syntax errors were including an extra parenthesis after atoi() and passing a total size to calloc() instead of an element count and element size. My solution is vulnerable to integer overflow and doesn't handle a negative row parameter. Simplifying assumptions: the first row and column will always be 1, so I don't recalculate it. Everything else just gets shifted in at the right. The code:

  #include <stdio.h>
  #include <stdlib.h>
  
  int main(int argc, char *argv[])
  {
  	int row;
  	int *data;
  	int i, j;
  
  	if(argc != 2) {
  		printf("Usage: %s <row>\n", argv[0]);
  		return -1;
  	}
  
  	row = atoi(argv[1]);
  	data = calloc(row, sizeof(int));
  
  	data[0] = 1;
  
  	for(i = 1; i < row; i++) {
  		for(j = i; j > 0; j--) {
  			data[j] = data[j] + data[j - 1];
  		}
  	}
  
  	for(i = 0; i < row; i++) {
  		printf("%d ", data[i]);
  	}
  	printf("\n");
  
  	return 0;
  }

There are no comments on this comment yet.