#include #include #include #include #include "matvec.h" // Allocates memory for the parmeter vector vec. Sets its data field // to point at a proper amount of memory and sets the len field // according to parameter len. Returns 0 on success and nonzero // if len is 0 or negative. int vector_init(vector_t *vec, long len){ if(len<=0){ printf("Invalid length: %ld\n",len); return 1; } vec->data = malloc(sizeof(int) * len); vec->len = len; return 0; } // Allocates memory for the parmeter matrix mat. Sets its data field // to point at a proper amount of memory and sets the rows,cols fields // according to parameters rows,cols. Returns 0 on success and nonzero // if rows,cols are 0 or negative. int matrix_init(matrix_t *mat, long rows, long cols){ if(rows<=0 || cols<=0){ printf("Invalid rows or cols: %ld %ld\n",rows,cols); return 1; } mat->data = malloc(sizeof(int) * rows * cols); mat->rows = rows; mat->cols = cols; return 0; } // Frees memory associated with the data field of vec. void vector_free_data(vector_t *vec){ free(vec->data); vec->len = -1; } // Frees memory associated with the data field of mat. void matrix_free_data(matrix_t *mat){ free(mat->data); mat->rows = -1; mat->cols = -1; } // Reads data from the specified file and initializes specified vector // with it. Allocated memory and checks for correct dimensions. The // format of the file is space separated numbers. // - first long indicates size of vector // - remaining ints are data in the vector // Returns 0 on success and non-zero on error. int vector_read_from_file(char *fname, vector_t *vec_ref){ FILE *file = fopen(fname,"r"); if(file == NULL){ perror("couldn't open vector file"); return 1; } long len; assert(fscanf(file, "%ld",&len)==1); vector_t vec; int ret = vector_init(&vec,len); if(ret){ return ret; } for(int i=0; idata[i*mat->cols + j]; } void mset(matrix_t *mat, int i, int j, int x){ mat->data[i*mat->cols + j] = x; } int vget(vector_t *vec, int i){ return vec->data[i]; } void vset(vector_t *vec, int i, int x){ vec->data[i] = x; } // state of the random number generator for phase09 unsigned long state = 1; // generate a random integer unsigned int pb_rand() { state = state * 1103515245 + 12345; return (unsigned int)(state/65536) % 32768; } // set seed for pb_rand() void pb_srand(unsigned long seed){ state = seed; } void vector_fill_random(vector_t vec, int max){ for(int i=0; i