How to resolve the algorithm Magic squares of singly even order step by step in the Java programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Magic squares of singly even order step by step in the Java programming language

Table of Contents

Problem Statement

A magic square is an NxN square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant). A magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6, 10, 14). This means that the subsquares have an odd size, which plays a role in the construction.

Create a magic square of 6 x 6.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Magic squares of singly even order step by step in the Java programming language

Magic Square Algorithm:

A magic square is a square grid filled with distinct numbers where the sum of each row, column, and diagonal is equal to the same constant. This code generates singly even magic squares, which are magic squares where all numbers are even except for the center number, which is odd.

MagicSquareSinglyEven Function:

The magicSquareSinglyEven function takes one argument:

  • n: The side length of the magic square (e.g., 4 for a 4x4 square).

It throws an IllegalArgumentException if n is less than 6 or if (n - 2) is not divisible by 4.

Algorithm Overview:

The algorithm creates a singly even magic square by:

  1. Creating a sub-square using the magicSquareOdd function. This sub-square is an odd-sized magic square (e.g., 3x3 for a 6x6 square).
  2. Duplicating and rotating the sub-square to fill in the entire magic square.
  3. Adding quadrant-specific factors to the numbers in each quadrant of the magic square to ensure that the magic constant is even.
  4. Swapping certain numbers in the left and right quadrants to complete the singly even magic square.

Implementation Details:

  • Sub-Square Generation: The magicSquareOdd function is called to generate an odd-sized magic square that serves as the basis for the singly even magic square.
  • Duplication and Rotation: The sub-square is duplicated and rotated to fill in the entire magic square. The result array is initialized as a 2D array with dimensions [n][n].
  • Quadrant Factors: The quadrantFactors array contains factors (0, 2, 3, 1) that are added to the numbers in each quadrant to ensure the magic constant is even.
  • Swapping Numbers: After duplicating and rotating the sub-square, some numbers in the left and right quadrants are swapped to complete the singly even magic square.

Output:

The program prints the generated magic square and the magic constant, which is the sum of the numbers in any row, column, or diagonal.

Example:

For n = 6 (a 6x6 magic square), the output would be:

8  2 22 86 5 46
82 12 26 7 27 95
84 25 3 35 93 10
73 87 49 19 36 52
47 91 51 21 34 79
23 78 92 54 77 11
Magic constant: 432

Note that the numbers in the magic square are all even except for the center number (3), which is odd. The sum of any row, column, or diagonal is 432, which is the magic constant.

Source code in the java programming language

public class MagicSquareSinglyEven {

    public static void main(String[] args) {
        int n = 6;
        for (int[] row : magicSquareSinglyEven(n)) {
            for (int x : row)
                System.out.printf("%2s ", x);
            System.out.println();
        }
        System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2);
    }

    public static int[][] magicSquareOdd(final int n) {
        if (n < 3 || n % 2 == 0)
            throw new IllegalArgumentException("base must be odd and > 2");

        int value = 0;
        int gridSize = n * n;
        int c = n / 2, r = 0;

        int[][] result = new int[n][n];

        while (++value <= gridSize) {
            result[r][c] = value;
            if (r == 0) {
                if (c == n - 1) {
                    r++;
                } else {
                    r = n - 1;
                    c++;
                }
            } else if (c == n - 1) {
                r--;
                c = 0;
            } else if (result[r - 1][c + 1] == 0) {
                r--;
                c++;
            } else {
                r++;
            }
        }
        return result;
    }

    static int[][] magicSquareSinglyEven(final int n) {
        if (n < 6 || (n - 2) % 4 != 0)
            throw new IllegalArgumentException("base must be a positive "
                    + "multiple of 4 plus 2");

        int size = n * n;
        int halfN = n / 2;
        int subSquareSize = size / 4;

        int[][] subSquare = magicSquareOdd(halfN);
        int[] quadrantFactors = {0, 2, 3, 1};
        int[][] result = new int[n][n];

        for (int r = 0; r < n; r++) {
            for (int c = 0; c < n; c++) {
                int quadrant = (r / halfN) * 2 + (c / halfN);
                result[r][c] = subSquare[r % halfN][c % halfN];
                result[r][c] += quadrantFactors[quadrant] * subSquareSize;
            }
        }

        int nColsLeft = halfN / 2;
        int nColsRight = nColsLeft - 1;

        for (int r = 0; r < halfN; r++)
            for (int c = 0; c < n; c++) {
                if (c < nColsLeft || c >= n - nColsRight
                        || (c == nColsLeft && r == nColsLeft)) {

                    if (c == 0 && r == nColsLeft)
                        continue;

                    int tmp = result[r][c];
                    result[r][c] = result[r + halfN][c];
                    result[r + halfN][c] = tmp;
                }
            }

        return result;
    }
}


  

You may also check:How to resolve the algorithm Singly-linked list/Traversal step by step in the AutoHotkey programming language
You may also check:How to resolve the algorithm Sort an integer array step by step in the Fōrmulæ programming language
You may also check:How to resolve the algorithm Set consolidation step by step in the VBA programming language
You may also check:How to resolve the algorithm Walk a directory/Recursively step by step in the Haskell programming language
You may also check:How to resolve the algorithm Sum and product of an array step by step in the Lasso programming language