Last active
August 29, 2015 14:14
-
-
Save markogresak/14686b4655c032a57a4d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// a) Definirajte strukturo, ki predstavlja matriko in še ustrezen tip matrix. Struktura naj hrani dimenzijo matrike (št. vrstic in stolpcev) in elemente matrike (tabela celih števil). Koliko bajtov zaseda ta struktura? | |
// b) Napišite funkcije za delo z matrikami, npr.: | |
// matrix* create_matrix(int n, int m, int val) | |
// Ustvari novo matriko velikosti n x m, njene elemente pa inicializira na val. | |
// matrix* create_random_matrix(int n, int m) | |
// Ustvari novo matriko velikosti n x m, njene elemente pa naključno inicializira. | |
// print_matrix(matrix* m) | |
// Podamo matriko m izpiše. | |
// matrix* read_matrix() | |
// S standardnega vhoda prebere dve števili, ki povesta dimenzijo matrike, nato pa še ustrezno število elementov. | |
// matrix* multiply(matrix* m1, matrix* m2) | |
// Vrne novo matriko, ki je produkt matrik m1 in m2. | |
// c) S pomočjo funkcij napišite program, ki naredi naslednje: | |
// Če je prvi argument enak R, potem izpiše naključno matriko velikosti N x M, kjer sta N in M drugi in tretji argument. | |
// Če je prvi argument M, potem program prebere dve matriki (iz standardnega vhoda), ju zmnoži in izpiše rezultat. | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
typedef struct matrix { | |
int n, m; | |
int* el; | |
} matrix; | |
matrix* create_matrix(int n, int m, int val) { | |
matrix* mtx = malloc(sizeof(matrix)); | |
mtx->n = n; | |
mtx->m = m; | |
mtx->el = malloc(sizeof(int) * n * m); | |
for(int i = 0; i < mtx->n * mtx->m; i++) | |
*(mtx->el + i) = val; | |
return mtx; | |
} | |
matrix* create_random_matrix(int n, int m) { | |
return create_matrix(n, m, 123); | |
} | |
matrix* read_matrix() { | |
return create_matrix(2, 3, 10); | |
} | |
void print_matrix(matrix* m) { | |
int* p = m->el; | |
for(int i = 0; i < m->m; i++) { | |
for(int i = 0; i < m->n; p++, i++) | |
printf("%d ", *p); | |
printf("\n"); | |
} | |
} | |
matrix* multiply(matrix* m1, matrix* m2) { | |
if(!(m1->n == m2->n && m1->m == m2->m)) | |
return NULL; | |
matrix* m = create_matrix(m1->n, m1->m, 0); | |
for(int i = 0; i < m->n * m->m; i++) | |
*(m->el + i) = *(m1->el + i) + *(m2->el + i); | |
return m; | |
} | |
int main(int argc, char const *argv[]) { | |
if(strcmp(argv[1], "R") == 0) | |
print_matrix(create_random_matrix(atoi(argv[2]), atoi(argv[3]))); | |
else if(strcmp(argv[1], "M") == 0) | |
print_matrix(multiply(read_matrix(), read_matrix())); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment