How to resolve the algorithm Magic squares of doubly even order step by step in the Go programming language
How to resolve the algorithm Magic squares of doubly even order step by step in the Go programming language
Table of Contents
Problem Statement
A magic square is an N×N 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 doubly even order has a size that is a multiple of four (e.g. 4, 8, 12).
This means that the subsquares also have an even size, which plays a role in the construction.
Create a magic square of 8 × 8.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Magic squares of doubly even order step by step in the Go programming language
The provided Go code generates and prints a magic square of a given dimension d
, which is a square matrix where the sum of each row, column, and diagonal is equal to a constant known as the magic constant. The code takes an integer d
as input and returns a 2D slice representing the magic square.
1. Constant and Variables:
- The code defines a constant
dimensions
with a value of 8, indicating the desired dimension of the magic square. - It declares a variable
bits
with the value0x9669
, a bitmask used for generating the magic square pattern. size
stores the total number of cells in the square, calculated asd * d
.mult
is set tod / 4
, which is used to determine the bit position for accessing the bitmask.
2. setupMagicSquareData
Function:
- This function takes an integer
d
representing the dimension of the square and returns a 2D slice[][]int
representing the magic square. - It checks if
d
is less than 4 or not divisible by 4, which are invalid dimensions for a magic square, and returns an error if true. - The function initializes an empty 2D slice
output
to store the square data. - It iterates over each row and column in the square using nested loops (outer loop for rows and inner loop for columns).
- For each cell, it calculates the bit position
bitPos
based on the column and row indices and themult
value. - Using bitwise operations on the
bits
bitmask, it determines whether to set the cell value toi+1
orsize-i
. This pattern generates the magic square. - The cell values are appended to their respective rows in
output
.
3. arrayItoa
Function:
- This function takes an integer array
input
and returns a string array where each integer is converted to a string. - It uses the
fmt.Sprintf
function to format each integer into a string with a fixed width of 4 characters. - The formatted strings are appended to the output array.
4. main
Function:
- The
main
function callssetupMagicSquareData(dimensions)
with the constantdimensions
(8) to generate the magic square data. - If there is an error, it prints the error and exits.
- It calculates the magic constant using the formula
(dimensions * (dimensions*dimensions + 1)) / 2
. - It iterates over the rows of the magic square data and prints each row as a space-separated string using
strings.Join
andarrayItoa
. - Finally, it prints the calculated magic constant.
Source code in the go programming language
package main
import (
"fmt"
"log"
"strings"
)
const dimensions int = 8
func setupMagicSquareData(d int) ([][]int, error) {
var output [][]int
if d < 4 || d%4 != 0 {
return [][]int{}, fmt.Errorf("Square dimension must be a positive number which is divisible by 4")
}
var bits uint = 0x9669 // 0b1001011001101001
size := d * d
mult := d / 4
for i, r := 0, 0; r < d; r++ {
output = append(output, []int{})
for c := 0; c < d; i, c = i+1, c+1 {
bitPos := c/mult + (r/mult)*4
if (bits & (1 << uint(bitPos))) != 0 {
output[r] = append(output[r], i+1)
} else {
output[r] = append(output[r], size-i)
}
}
}
return output, nil
}
func arrayItoa(input []int) []string {
var output []string
for _, i := range input {
output = append(output, fmt.Sprintf("%4d", i))
}
return output
}
func main() {
data, err := setupMagicSquareData(dimensions)
if err != nil {
log.Fatal(err)
}
magicConstant := (dimensions * (dimensions*dimensions + 1)) / 2
for _, row := range data {
fmt.Println(strings.Join(arrayItoa(row), " "))
}
fmt.Printf("\nMagic Constant: %d\n", magicConstant)
}
You may also check:How to resolve the algorithm Van der Corput sequence step by step in the Perl programming language
You may also check:How to resolve the algorithm Non-decimal radices/Convert step by step in the Smalltalk programming language
You may also check:How to resolve the algorithm Closest-pair problem step by step in the AutoHotkey programming language
You may also check:How to resolve the algorithm Munchausen numbers step by step in the Picat programming language
You may also check:How to resolve the algorithm Sierpinski carpet step by step in the ERRE programming language