Last active
June 2, 2018 10:00
-
-
Save espositodaniele/54aa880c35cc28eff1ea65c8e03602a0 to your computer and use it in GitHub Desktop.
C program to check if the generated matrix is a magic squadre
This file contains hidden or 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
#include <stdio.h> | |
#include <time.h> /* for time() */ | |
#include <stdlib.h> /* for rand() and srand() */ | |
int check_square(int square[][100], int ); | |
void generate(int matrix[][100], int ); | |
int main() { | |
int size_matrix = 100, magic_square = 0, successi = 0; | |
int matrix[100][100]; | |
printf("Inserire la dimensione del quadrato: "); | |
scanf("%d", &size_matrix); | |
generate(matrix, size_matrix); // generating random matrix | |
for (int i = 0; i < 1000; ++i) { | |
if (check_square(matrix, size_matrix)) { | |
magic_square++; | |
}; | |
} | |
//calculate percentage of success | |
successi = magic_square / 1000 * 100; | |
printf("La percentuale di successi è: %d %%", magic_square); | |
} | |
int check_square(int square[][100], int size ){ | |
int rowsum, columnsum, diagonalsum = 0, diagonalminsum = 0, compare = 0; | |
for(int i = 0; i < size; i++) | |
{ | |
//calculate diagonal min and diagonal mag | |
diagonalsum += square[i][i]; | |
diagonalminsum += square[i][size-1-i]; | |
rowsum = 0; | |
columnsum = 0; | |
for(int j = 0; j < size; j++) | |
{ | |
rowsum += square[i][j]; | |
columnsum += square[j][i]; | |
} | |
//Get a copy of the first row | |
if (i == 0) { | |
compare = rowsum; | |
} | |
//Check if the rows and columns are all equal | |
if (compare != rowsum || compare != columnsum) { | |
return 0; | |
} | |
} | |
if (diagonalsum != compare || diagonalminsum != compare) { | |
return 0; | |
} | |
return 1; | |
}; | |
//Function to generate random matrix | |
void generate (int matrix[][100], int size_matrix) { | |
srand(time(NULL)); // creating random matrix | |
for ( int i = 0; i < size_matrix; i++) { | |
for ( int j = 0; j < size_matrix; j++) { | |
matrix[i][j] = rand() % 10 + 1; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment