feat: Initial commit
This commit is contained in:
89
Laboratorio 2/Esercizio 2/main.c
Normal file
89
Laboratorio 2/Esercizio 2/main.c
Normal file
@@ -0,0 +1,89 @@
|
||||
// Laboratorio 2 - Esercizio 2
|
||||
// Matteo Schiff - s295565
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
int ** matrmalloc(int * nc, int * nr) {
|
||||
FILE *fp_read;
|
||||
|
||||
if ((fp_read = fopen("mat.txt", "r")) == NULL)
|
||||
{
|
||||
puts("Impossibile aprire il file");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
fscanf(fp_read, "%u %u\n", nr, nc);
|
||||
|
||||
int ** mat = malloc(*nr * sizeof(int *));
|
||||
|
||||
for (int i = 0; i < *nr; i++) {
|
||||
int * row = malloc(*nc * sizeof(int));
|
||||
for (int j = 0; j < *nc; j++) {
|
||||
fscanf(fp_read, "%d ", &row[j]);
|
||||
}
|
||||
mat[i] = row;
|
||||
}
|
||||
|
||||
fclose(fp_read);
|
||||
return mat;
|
||||
}
|
||||
|
||||
void matrfree(int **mat, int nr) {
|
||||
for (int i = 0; i < nr; i++) {
|
||||
free(mat[i]);
|
||||
}
|
||||
|
||||
free(mat);
|
||||
}
|
||||
|
||||
void separa(int **mat, int nr, int nc, int ** bianchi, int ** neri, int * nbianchi, int * nneri) {
|
||||
int a = nc % 2;
|
||||
int x = nc / 2;
|
||||
int b = nr % 2;
|
||||
int y = nr / 2;
|
||||
|
||||
*nneri = (x + a) * y + x * (y + b);
|
||||
*nbianchi = x * y + (x+a) * (y + b);
|
||||
|
||||
*bianchi = malloc(*nbianchi * sizeof(int));
|
||||
*neri = malloc(*nneri * sizeof(int));
|
||||
|
||||
int conta_bianchi = 0, conta_neri = 0;
|
||||
|
||||
for (int i = 0; i < nr; i++) {
|
||||
for (int j = 0; j < nc; j++) {
|
||||
if ((i+j) % 2 == 0) {
|
||||
(*bianchi)[conta_bianchi++] = mat[i][j];
|
||||
} else {
|
||||
(*neri)[conta_neri++] = mat[i][j];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char ** argv) {
|
||||
int nc, nr;
|
||||
int ** mat = matrmalloc(&nc, &nr);
|
||||
|
||||
if (mat == NULL) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
int *bianchi, *neri, n_bianchi, n_neri;
|
||||
separa(mat, nr, nc, &bianchi, &neri, &n_bianchi, &n_neri);
|
||||
|
||||
puts("Numeri su caselle bianche:");
|
||||
for (int i = 0; i < n_bianchi; i++)
|
||||
printf("%u\n", bianchi[i]);
|
||||
|
||||
puts("Numeri su caselle nere:");
|
||||
for (int i = 0; i < n_neri; i++)
|
||||
printf("%u\n", neri[i]);
|
||||
|
||||
matrfree(mat, nr);
|
||||
free(bianchi);
|
||||
free(neri);
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user