Skip to content

Instantly share code, notes, and snippets.

@JosiasAurel
Created June 9, 2022 14:08
Show Gist options
  • Save JosiasAurel/f1a76aa4902e787d40fc5c92d3640fbc to your computer and use it in GitHub Desktop.
Save JosiasAurel/f1a76aa4902e787d40fc5c92d3640fbc to your computer and use it in GitHub Desktop.
#include <stdio.h>
#define N 5
static int A[N][N];
void fillMagicSquare();
typedef struct TupleTwo
{
int i;
int j;
} TupleTwo;
int main()
{
fillMagicSquare();
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
printf("%d ", A[i][j]);
}
puts("");
}
return 0;
}
void fillMagicSquare()
{
int M = (N*((N*N)+1))/2;
printf("Magic Number %d \n", M);
int count = 0;
TupleTwo position = { .i = N/2, .j = N-1 };
while (count < N*N)
{
A[position.i][position.j] = count+1;
// compute the next position
position.i -= 1;
position.j += 1;
if (position.i == -1 && position.j == N)
{
position.i = 0;
position.j = N-2;
} else {
position.i = position.i == -1 ? N-1 : position.i;
position.j = position.j == N ? 0 : position.j;
}
if (A[position.i][position.j])
{
position.j -= 2;
position.i += 1;
}
count++;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment