December 2005 Problem 'pktri1' Analysis

by Rob Kolstad

This problem has several approaches. The goal in contest programming is to write a solution that is almost guaranteed to work properly first time -- and to do so quickly.

This solution first fills in a matrix (mnemonically named 'matrix') with the proper digits. The second loop prints the matrix with the appropriate number of spaces in front of the digits.

Here is Rob's solution:

#include <stdio.h>
int matrix[20][20];
main () {
    FILE *fin  = fopen ("pktri1.in", "r");
    FILE *fout = fopen ("pktri1.out", "w");
    int n, s, r, c;
    fscanf (fin, "%d %d", &n, &s);
    for (c = 0; c < n; c++) {
        for (r = 0; r <= c; r++) {
	    matrix[r][c] = s++;
	    if (s == 10) s = 1;
	}
    }
    for (r = 0; r < n; r++) {
	for (c = 0; c < r;  c++) {
	    if (c > 0) fprintf (fout, " ");
	    fprintf (fout, " ");
	}
        for (c = r; c < n; c++) {
	    if (c > 0) fprintf (fout, " ");
	    fprintf (fout, "%d", matrix[r][c]);
	}
	fprintf(fout, "\n");
    }
    exit (0);
}