Skip to content
Snippets Groups Projects
main.c 2.79 KiB
#include <stdio.h>

#define ROWS(a) (sizeof(a) / sizeof(a[0]))
#define COLS(a) (sizeof(a[0]) / sizeof(a[0][0]))

void input(int rows, int cols, int matrix[][cols]) {
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            printf("[%d][%d]: ", i, j);
            scanf("%d", &matrix[i][j]);
        }
    }
}

int count_eq(int rows, int cols, int matrix[][cols], int key) {
    int ret = 0;
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            if (matrix[i][j] == key) {
                ++ret;
            }
        }
    }
    return ret;
}

int sum(
        int rows1, int cols1, int a1[][cols1],
        int rows2, int cols2, int a2[][cols2],
        int rows3, int cols3, int a3[][cols3]) 
{
    int ret;
    if (rows1 == rows2 && rows2 == rows3 && cols1 == cols2 && cols2 == cols3) {
        int rows = rows1;
        int cols = cols1;

        for (int i = 0; i < rows; ++i) {
            for (int j = 0; j < cols; ++j) {
                a3[i][j] = a1[i][j] + a2[i][j];
            }
        }

        ret = 0;
    } else {
        ret = -1;
    }
    return ret;
}

void print(int rows, int cols, int matrix[][cols]) {
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            printf("%3d ", matrix[i][j]);
        }
        puts("");
    }
}


int multiply(
        int rows1, int cols1, int a1[][cols1],
        int rows2, int cols2, int a2[][cols2],
        int rows3, int cols3, int a3[][cols3]) 
{
    int ret;
    if (cols1 == rows2 && rows1 == rows3 && cols2 == cols3) {
        for (int i = 0; i < rows1; ++i) {
            for (int j = 0; j < cols2; ++j) {

                int sum = 0;
                for (int k = 0; k < rows2; ++k) {
                    sum += a1[i][k] * a2[k][j];
                }
                a3[i][j] = sum;

            }
        }

        ret = 1;
    } else {
        ret = -1;
    }

    return ret;
}

int main(void) {
    int a1[2][3];
    int a2[3][2];

    puts("inserimento A");
    input(ROWS(a1), COLS(a1), a1);
    puts("inserimento B");
    input(ROWS(a2), COLS(a2), a2);

    int x;
    printf("inserire x: ");
    scanf("%d", &x);
    printf("instanze di %d in A: %d\n", x, count_eq(ROWS(a1), COLS(a1), a1, x));

    int y;
    printf("inserire y: ");
    scanf("%d", &y);
    printf("instanze di %d in B: %d\n", y, count_eq(ROWS(a2), COLS(a2), a2, y));

    int s[ROWS(a1)][COLS(a1)];
    if (sum(ROWS(a1), COLS(a1), a1, ROWS(a2), COLS(a2), a2, ROWS(s), COLS(s), s) < 0) {
        fputs("somma impossibile\n", stderr);
    } else {
        print(ROWS(s), COLS(s), s);
    }

    int m[2][2];
    if (multiply(ROWS(a1), COLS(a1), a1, ROWS(a2), COLS(a2), a2, ROWS(m), COLS(m), m) < 0) {
        fputs("prodotto impossibile\n", stderr);
    } else {
        print(ROWS(m), COLS(m), m);
    }
}