Please, help me I need to make it with Srand (random) 450 Chapter 7 Arrays 8. Lo
ID: 3723812 • Letter: P
Question
Please, help me
I need to make it with Srand (random)
450 Chapter 7 Arrays 8. Lo Shu Magic Square The Lo Shu Magic Square is a grid with 3 rows and 3 columns shown in Figure 7-19. The Lo Shu Magic Square has the following properties: The grid contains the numbers 1 through 9 exactly . The sum of each row, each column, and each diagonal all add up to the same number. This is shown in Figure 7-20. In a program you can simulate a magic square using a two-dimensional array. Write a the array is a Lo Shu Magic Square. Test the function in a program! Figure 7.19 9 2 3 5 7 8 6Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
int main()
{
srand(time(NULL));
int grid[3][3] = {{2, 7, 6}, {9, 5, 1}, {4, 3, 8}}, i, j;
//shuffling array using rand() and RAND MAX
size_t k;
for (k = 0; k < 9; k++)
{
size_t j = k + rand() / (RAND_MAX / (9 - k) + 1);
int t = grid[j / 3][j % 3];
grid[j / 3][j % 3] = grid[i / 3][i % 3];
grid[i / 3][i % 3] = t;
}
//printing grid
printf("Generated grid is: ");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
printf("%d ", grid[i][j]);
printf(" ");
}
//initilizing row sum = 0;
int row_sum = 0;
for (i = 0; i < 3; i++)
{
int sum = 0;
for (j = 0; j < 3; j++)
{
sum += grid[i][j];
}
//checking rows sum equals to sum or not
if (i != 0 && row_sum != sum)
{
printf("not a Lo Shu Magic squre ");
exit(1);
}
row_sum = sum;
}
//checking columns sum equals to previous row sum or not
for (i = 0; i < 3; i++)
{
int sum = 0;
for (j = 0; j < 3; j++)
{
sum += grid[j][i];
}
if (row_sum != sum)
{
printf("not a Lo Shu Magic squre ");
exit(1);
}
row_sum = sum;
}
//find out diagnols sum
int diag1 = grid[0][0] + grid[1][1] + grid[2][2];
int diag2 = grid[0][2] + grid[1][1] + grid[2][0];
//checking diagnol sum equal to row sum or not
if (diag1 == diag2 && diag2 == row_sum)
printf("Lo Shu Magic squre ");
else
printf("not a Lo Shu Magic squre ");
return 0;
}