Gauss algorithmus part 1
This commit is contained in:
parent
f28846ca79
commit
77abcfee85
1 changed files with 82 additions and 0 deletions
82
gauss.c
Normal file
82
gauss.c
Normal file
|
@ -0,0 +1,82 @@
|
|||
#include <stdio.h>
|
||||
#include <assert.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
typedef struct {
|
||||
int ** data;
|
||||
int size;
|
||||
} Matrix;
|
||||
|
||||
Matrix matCreate(int size) {
|
||||
int** data = malloc(sizeof(int*) * size);
|
||||
for(unsigned int row = 0; row < size; row++) data[row] = malloc(sizeof(int)*size);
|
||||
return (Matrix){data,size};
|
||||
}
|
||||
|
||||
void matSet(Matrix m, size_t row, size_t col, int v) {
|
||||
assert(row < m.size);
|
||||
assert(col < m.size);
|
||||
m.data[row][col] = v;
|
||||
}
|
||||
|
||||
int matGet(Matrix m, size_t row, size_t col) {
|
||||
assert(row < m.size);
|
||||
assert(col < m.size);
|
||||
return m.data[row][col];
|
||||
}
|
||||
|
||||
void matSwapRows(Matrix m, size_t row1, size_t row2) {
|
||||
assert(row1 < m.size);
|
||||
assert(row2 < m.size);
|
||||
int* tmp = m.data[row1];
|
||||
m.data[row1] = m.data[row2];
|
||||
m.data[row2] = tmp;
|
||||
}
|
||||
|
||||
void matPrint(Matrix m) {
|
||||
for(unsigned int row = 0; row < m.size; row++) {
|
||||
for(unsigned int col = 0; col < m.size; col++) {
|
||||
printf("%02d ", matGet(m,row,col));
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
}
|
||||
|
||||
void matFree(Matrix m) {
|
||||
for(unsigned int row = 0; row < m.size; row++) free(m.data[row]);
|
||||
free(m.data);
|
||||
}
|
||||
|
||||
int reorder_mat(Matrix m, int rowCol) {
|
||||
if(rowCol >= m.size) return 1;
|
||||
if(matGet(m,rowCol,rowCol) != 0) return reorder_mat(m,rowCol+1);
|
||||
|
||||
for(int candidate = rowCol+1; candidate < m.size; candidate++) {
|
||||
if(matGet(m,candidate, rowCol) != 0) {
|
||||
matSwapRows(m, rowCol, candidate);
|
||||
if(reorder_mat(m, rowCol+1)) return 1;
|
||||
matSwapRows(m, rowCol, candidate);
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main( int argc, char *argv[] ) {
|
||||
|
||||
Matrix m = matCreate(2);
|
||||
matSet(m,0,0,0);
|
||||
matSet(m,0,1,1);
|
||||
matSet(m,1,0,1);
|
||||
matSet(m,1,1,0);
|
||||
|
||||
matPrint(m);
|
||||
|
||||
if(!reorder_mat(m,0)) {
|
||||
printf("Failed\n");
|
||||
}
|
||||
|
||||
matPrint(m);
|
||||
|
||||
return 0;
|
||||
}
|
Loading…
Reference in a new issue