graphprogram/matrix.c

79 lines
2.3 KiB
C
Raw Normal View History

2024-10-04 01:03:39 +02:00
#include <stddef.h>
2024-09-26 14:32:20 +02:00
#include <stdint.h>
#include <stdio.h>
2024-10-04 01:03:39 +02:00
#include <stdlib.h>
#include <string.h>
2024-10-04 13:05:02 +02:00
#include <time.h>
2024-09-26 14:32:20 +02:00
2024-10-04 01:03:39 +02:00
void print_matrix(const uint64_t row_length, const uint64_t column_length, const uint64_t matrix[row_length][column_length]) {
2024-10-03 12:48:22 +02:00
for (uint64_t column_index=0; column_index < column_length; column_index++) {
for (uint64_t row_index=0; row_index < row_length; row_index++) {
2024-09-26 14:32:20 +02:00
printf("%lu ", matrix[row_index][column_index]);
}
printf("\n");
}
}
2024-10-03 12:48:22 +02:00
2024-10-04 01:03:39 +02:00
int matrix_multiply_basic(const uint64_t row_length1, const uint64_t column_length1, const uint64_t matrix1[row_length1][column_length1],
const uint64_t row_length2, const uint64_t column_length2, const uint64_t matrix2[row_length2][column_length2],
2024-10-03 12:48:22 +02:00
uint64_t output_matrix[row_length1][column_length2]) {
2024-10-04 01:03:39 +02:00
if (row_length1 != column_length2) {
return 1;
}
2024-10-04 16:46:40 +02:00
uint64_t sum;
2024-10-04 01:03:39 +02:00
for (uint64_t i = 0; i < row_length1; i++) {
for(uint64_t j = 0; j < column_length2; j++) {
2024-10-04 16:46:40 +02:00
sum = 0;
2024-10-04 01:03:39 +02:00
for (uint64_t k = 0; k <row_length1; k++) {
sum += matrix1[i][k] * matrix2[k][j];
}
output_matrix[i][j] = sum;
}
}
return 0;
}
int read_csv(const char *file_name, const uint64_t row_length, const uint64_t column_length, uint64_t output_matrix[row_length][column_length]) {
FILE *file_ptr;
2024-10-04 16:46:40 +02:00
uint64_t bufsize = row_length*2; // have to account for delimiters
2024-10-04 13:05:02 +02:00
char buffer[bufsize];
char *value, *file_line;
uint64_t row_index = 0, column_index = 0;
2024-10-04 01:03:39 +02:00
file_ptr = fopen(file_name, "r");
if (file_ptr == NULL) {
printf("Unable to open csv\n");
return 1;
}
2024-10-04 13:05:02 +02:00
while ((file_line = fgets(buffer, bufsize, file_ptr)) != NULL) {
// This shit is just needed and I dont know why
file_line[strcspn(file_line, "\n")] = 0;
value = strtok(file_line, ";,");
// for some reason there are two NULLs at the end of a line
// and I dont wanna increment the column_index
if (value == NULL) {
continue;
2024-10-04 01:03:39 +02:00
}
2024-10-04 13:05:02 +02:00
while (value != NULL) {
output_matrix[row_index++][column_index] = strtoul(value, NULL, 0);
value = strtok(NULL, ";,");
2024-10-04 01:03:39 +02:00
}
2024-10-04 13:05:02 +02:00
row_index = 0;
column_index++;
}
2024-10-04 01:03:39 +02:00
fclose(file_ptr);
2024-10-03 12:48:22 +02:00
2024-10-04 01:03:39 +02:00
return 0;
2024-10-03 12:48:22 +02:00
}