Programmeringsmetodik-tentamen 2010-11-04: Programmet matrix-brightest.c

Ladda ner

/* matrix-brightest.c */

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

#ifdef _WIN32
    #include <conio.h>
#endif

#define SENSOR_SIDE 1024

/* Will be automatically set to all zero, so we don't really need init_sensor */
double sensor[SENSOR_SIDE][SENSOR_SIDE];

void init_sensor(void) {
    int x, y;
    for (x = 0; x < SENSOR_SIDE; ++x)
        for (y = 0; y < SENSOR_SIDE; ++y)
            sensor[x][y] = 0.0;
}

void add_measurement(int x, int y, double value) {
    sensor[x][y] += value;
}

void find_brightest_point(int *xp, int *yp) {
    int x, y;
    double brightest_so_far = 0.0;
    int brightest_x_so_far = -1;
    int brightest_y_so_far = -1;
    for (x = 0; x < SENSOR_SIDE; ++x) {
        for (y = 0; y < SENSOR_SIDE; ++y) {
            if (sensor[x][y] > brightest_so_far) {
                brightest_so_far = sensor[x][y];
                brightest_x_so_far = x;
                brightest_y_so_far = y;
            }
        }
    }
    *xp = brightest_x_so_far;
    *yp = brightest_y_so_far;
}

int main(void) {
    char file_name[1000];
    FILE *tsin;
    int x, y;
    double brightness;
    long int number;

    printf("Data file name: ");
    fgets(file_name, sizeof file_name, stdin);
    /* Get rid of the trailing newline character from fgets */
    if (file_name[strlen(file_name) - 1] == '\n')
        file_name[strlen(file_name) - 1] = '\0';
    tsin = fopen(file_name, "r");
    if (tsin == NULL) {
        fprintf(stderr, "Couldn't read the data file '%s'.\n", file_name);
        fprintf(stderr, "Possible cause: %s (error code %d).\n", strerror(errno), errno);
        #ifdef _WIN32
            _getch();
        #endif 
        exit(EXIT_FAILURE);
    }

    number = 0;
    printf("Reading data from from '%s'...\n", file_name);
    while (fscanf(tsin, "%d %d %lf", &x, &y, &brightness) == 3) {
        add_measurement(x, y, brightness);
        ++number;
    }
    fclose(tsin);
    printf("Finished reading %ld measurements from '%s'.\n", number, file_name);

    printf("Finding brightest point...\n");
    find_brightest_point(&x, &y);
    printf("Brightest point: x=%d, y=%d, value=%f\n", x, y, sensor[x][y]);

    #ifdef _WIN32
        _getch();
    #endif

    return EXIT_SUCCESS;
}


Thomas Padron-McCarthy (thomas.padron-mccarthy@oru.se), 3 november 2010