Skip to content

Instantly share code, notes, and snippets.

@devkoriel
Last active October 6, 2017 10:56
Show Gist options
  • Save devkoriel/c5abbaeb4c8f149fbbc66b5d976c4f4b to your computer and use it in GitHub Desktop.
Save devkoriel/c5abbaeb4c8f149fbbc66b5d976c4f4b to your computer and use it in GitHub Desktop.
Calculate determinant by recursive method.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <malloc.h>
struct matrix_t {
int height;
int width;
int** data;
};
matrix_t* reduce(matrix_t* matrix, int order) {
int reduced_height = matrix->height - 1;
int reduced_width = reduced_height;
struct matrix_t* reduced = (matrix_t*)malloc(sizeof(struct matrix_t));
reduced->height = reduced_height;
reduced->width = reduced_width;
reduced->data = (int**)malloc(sizeof(int*) * reduced_height);
for (int i = 0; i < reduced_height; i++) {
reduced->data[i] = (int*)malloc(sizeof(int) * reduced_width);
}
int index = 0;
for (int i = 1; i < matrix->height; i++) {
index = 0;
for (int j = 0; j < matrix->width; j++) {
if (j != order) {
reduced->data[i - 1][index] = matrix->data[i][j];
++index;
}
}
}
return reduced;
}
int det(matrix_t* matrix) {
int out = 0;
if (matrix->height == 1 && matrix->width == 1) return matrix->data[0][0];
for (int order = 0; order < matrix->width; order++) {
out += (order % 2 == 0 ? 1 : -1) * matrix->data[0][order] * det(reduce(matrix, order));
}
for (int i = 0; i < matrix->width; i++) {
free(matrix->data[i]);
}
free(matrix->data);
free(matrix);
return out;
}
int main() {
struct matrix_t* matrix = (matrix_t*)malloc(sizeof(struct matrix_t));
matrix->height = 3;
matrix->width = matrix->height;
matrix->data = (int**)malloc(sizeof(int*) * matrix->height);
for (int i = 0; i < matrix->height; i++) {
matrix->data[i] = (int*)malloc(sizeof(int) * matrix->width);
for (int j = 0; j < matrix->width; j++) {
matrix->data[i][j] = rand();
}
}
for (int i = 0; i < matrix->height; i++) {
for (int j = 0; j < matrix->width; j++) {
printf("%d ", matrix->data[i][j]);
}
printf("\n");
}
printf("Determinant: %d\n", det(matrix));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment