119 lines
2.6 KiB
C
119 lines
2.6 KiB
C
// Laboratorio 4 - Esercizio 3
|
|
// Matteo Schiff - s295565
|
|
|
|
#include <stdio.h>
|
|
#include <ctype.h>
|
|
#define MAX_N 20
|
|
|
|
int min(int a, int b);
|
|
int stampaSottomatrice(int m[MAX_N][MAX_N], int x, int y, int dim);
|
|
void sottomatrici(int M[MAX_N][MAX_N], int nr, int nc, int dim);
|
|
int leggiMatrice(int M[MAX_N][MAX_N], int * nr, int * nc);
|
|
|
|
int min(int a, int b) {
|
|
if (a < b)
|
|
return a;
|
|
|
|
return b;
|
|
}
|
|
|
|
|
|
// La funzione stampa la sottomatrice e restituisce la somma degli elementi
|
|
int stampaSottomatrice(int m[MAX_N][MAX_N], int x, int y, int dim) {
|
|
int sum = 0;
|
|
for (int i = x; i < x + dim; i++) {
|
|
for (int j = y; j < y + dim; j++) {
|
|
printf("%d ", m[i][j]);
|
|
sum += m[i][j];
|
|
}
|
|
putc('\n', stdout);
|
|
}
|
|
putc('\n', stdout);
|
|
|
|
return sum;
|
|
}
|
|
|
|
void sottomatrici(int M[MAX_N][MAX_N], int nr, int nc, int dim) {
|
|
int a, max = 0;
|
|
int x = -1, y = -1;
|
|
|
|
printf("Le sottomatrici quadrate di dimensione %d sono:\n", dim);
|
|
|
|
for (int i = 0; i <= nr - dim; i++) {
|
|
for (int j = 0; j <= nc - dim; j++) {
|
|
a = stampaSottomatrice(M, i, j, dim);
|
|
|
|
if (a >= max) {
|
|
max = a;
|
|
x = i;
|
|
y = j;
|
|
}
|
|
}
|
|
}
|
|
|
|
printf("La sottomatrice con somma degli elementi massima (%d) e':\n", max);
|
|
stampaSottomatrice(M, x, y, dim);
|
|
}
|
|
|
|
int leggiMatrice(int M[MAX_N][MAX_N], int * nr, int * nc) {
|
|
char filename[23] = "./";
|
|
FILE *fp_read;
|
|
|
|
puts("Inserisci il nome del file");
|
|
scanf("%20s", filename + 2);
|
|
|
|
|
|
fp_read = fopen(filename, "r");
|
|
|
|
if (fp_read == NULL)
|
|
{
|
|
printf("Errore nell'apertura del file\n");
|
|
return 1;
|
|
}
|
|
|
|
fscanf(fp_read, "%d %d\n", nr, nc);
|
|
|
|
// Controlla dimensione matrice
|
|
if (*nr < 0 || *nc < 0 || *nr > MAX_N || *nc > MAX_N) {
|
|
printf("Dimensione della matrice non valida\n");
|
|
fclose(fp_read);
|
|
return 1;
|
|
}
|
|
|
|
// Leggi matrice
|
|
for (int i = 0; i < *nr; i++) {
|
|
for (int j = 0; j < *nc; j++) {
|
|
fscanf(fp_read, "%d ", &M[i][j]);
|
|
}
|
|
}
|
|
|
|
fclose(fp_read);
|
|
return 0;
|
|
}
|
|
|
|
int main()
|
|
{
|
|
int M[MAX_N][MAX_N], N, P, dir, lmax, dim, nr, nc;
|
|
|
|
if (leggiMatrice(M, &nr, &nc)) {
|
|
return 1;
|
|
}
|
|
|
|
lmax = min(nr, nc);
|
|
|
|
// Chiedi all'utente le dimensioni dei sottoquadrati
|
|
while (1) {
|
|
printf("Inserisci una dimensione compresa tra 1 e %d: ", lmax);
|
|
scanf("%d", &dim);
|
|
|
|
// Se dim non è un valore valido, termina
|
|
if (dim < 1 || dim > lmax) {
|
|
break;
|
|
}
|
|
|
|
sottomatrici(M, nr, nc, dim);
|
|
}
|
|
|
|
return 0;
|
|
}
|