/// <summary> /// Creates a jagged magic square matrix. /// </summary> /// public static double[][] Magic(int size) { return(Matrix.Magic(size).ToJagged()); }
/// <summary> /// Creates a magic square matrix. /// </summary> public static double[,] Magic(int size) { if (size < 3) { throw new ArgumentOutOfRangeException("size", size, "The square size must be greater or equal to 3."); } double[,] matrix = new double[size, size]; // First algorithm: Odd order if ((size % 2) == 1) { int a = (size + 1) / 2; int b = (size + 1); for (int j = 0; j < size; j++) { for (int i = 0; i < size; i++) { matrix[i, j] = size * ((i + j + a) % size) + ((i + 2 * j + b) % size) + 1; } } } // Second algorithm: Even order (double) else if ((size % 4) == 0) { for (int j = 0; j < size; j++) { for (int i = 0; i < size; i++) { if (((i + 1) / 2) % 2 == ((j + 1) / 2) % 2) { matrix[i, j] = size * size - size * i - j; } else { matrix[i, j] = size * i + j + 1; } } } } // Third algorithm: Even order (single) else { int n = size / 2; int p = (size - 2) / 4; double t; double[,] block = Matrix.Magic(n); for (int j = 0; j < n; j++) { for (int i = 0; i < n; i++) { double e = block[i, j]; matrix[i, j] = e; matrix[i, j + n] = e + 2 * n * n; matrix[i + n, j] = e + 3 * n * n; matrix[i + n, j + n] = e + n * n; } } for (int i = 0; i < n; i++) { // Swap M[i,j] and M[i+n,j] for (int j = 0; j < p; j++) { t = matrix[i, j]; matrix[i, j] = matrix[i + n, j]; matrix[i + n, j] = t; } for (int j = size - p + 1; j < size; j++) { t = matrix[i, j]; matrix[i, j] = matrix[i + n, j]; matrix[i + n, j] = t; } } // Continue swaping in the boundary t = matrix[p, 0]; matrix[p, 0] = matrix[p + n, 0]; matrix[p + n, 0] = t; t = matrix[p, p]; matrix[p, p] = matrix[p + n, p]; matrix[p + n, p] = t; } return(matrix); // return the magic square. }
/// <summary> /// Creates a jagged magic square matrix. /// </summary> /// public static double[][] Magic(int size) { return(Matrix.Magic(size).ToArray()); }