diff --git a/.gitignore b/.gitignore index 7353e7e145139bbcfb99384df098facea1844fb9..08fa83eda48f7f55c26acd21c399f6329bae49d7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ build *.o +*.txt diff --git a/ex1/Makefile b/ex1/Makefile index b08d3eb29536ccd9e3196c3f17b095510ef119e6..def2451963d1c28b0d80b76116377d6e3b7de279 100644 --- a/ex1/Makefile +++ b/ex1/Makefile @@ -10,8 +10,8 @@ CC := gcc CFLAGS := -std=c11 -Wall -Wextra -pedantic CFLAGS_DEBUG := ${CFLAGS} -fsanitize=address -fsanitize=leak -g -DDEBUG -LDEXTRA := -LDEXTRA_DEBUG := +LDEXTRA := -lm +LDEXTRA_DEBUG := -lm LDFLAGS := ${CFLAGS} ${LDEXTRA} LDFLAGS_DEBUG := ${CFLAGS_DEBUG} ${LDEXTRA_DEBUG} diff --git a/ex1/ex1.c b/ex1/ex1.c index 68c42f87925707af4c7b24501335064cba34549a..124112e9c08ae47cc70a9f95a45fce9ed237f1c1 100644 --- a/ex1/ex1.c +++ b/ex1/ex1.c @@ -1,6 +1,81 @@ +#include <math.h> #include <stdio.h> #include <stdlib.h> +#define ROWS 5 +#define COLS 4 +#define ITERATIONS 10 + + +double** alloc(const int m, const int n) { + double** a = malloc(m * sizeof(double*)); + for (int i = 0; i < n; ++i) { + a[i] = malloc(n * sizeof(double)); + } + return a; +} + +void destroy(double** a, const int m) { + for (int i = 0; i < m; ++i) { + free(a[i]); + } + free(a); +} + +void init(double** a, const int m, const int n) { + for (int y = 0; y < m; ++y) { + for (int x = 0; x < n; ++x) { + a[y][x] = sqrt(y + x); + } + } +} + +void mean(double** a, const int m, const int n, double** r) { + for (int y = 0; y < m; ++y) { + for (int x = 0; x < n; ++x) { + if ( + (y == 0) | + (y == (m - 1)) | + (x == 0) | + (x == (n - 1)) + ) { + r[y][x] = a[y][x]; + } else { + r[y][x] = ( + a[y][x + 1] + + a[y][x - 1] + + a[y + 1][x] + + a[y - 1][x] + + a[y][x] + ) / 5.0; + } + } + } +} + +void print(double** a, const int m, const int n) { + for (int y = 0; y < m; ++y) { + for (int x = 0; x < n; ++x) { + printf("%lf", a[y][x]); + } + printf("\n"); + } +} + int main() { + double** m = alloc(ROWS, COLS); + double** n = alloc(ROWS, COLS); + init(m, ROWS, COLS); + double** swap; + for (int i = 0; i < ITERATIONS; ++i) { + mean(m, ROWS, COLS, n); + swap = m; + m = n; + n = swap; + } + print(m, ROWS, COLS); + destroy(m, ROWS); + destroy(n, ROWS); + return EXIT_SUCCESS; }