How to resolve the algorithm Magic squares of doubly even order step by step in the Scala programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Magic squares of doubly even order step by step in the Scala 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 Scala programming language
Source code in the scala programming language
object MagicSquareDoublyEven extends App {
private val n = 8
private def magicSquareDoublyEven(n: Int): Array[Array[Int]] = {
require(n >= 4 || n % 4 == 0, "Base must be a positive multiple of 4.")
// pattern of count-up vs count-down zones
val (bits, mult, result, size) = (38505, n / 4, Array.ofDim[Int](n, n), n * n)
var i = 0
for (r <- result.indices; c <- result(0).indices) {
def bitPos = c / mult + (r / mult) * 4
result(r)(c) = if ((bits & (1 << bitPos)) != 0) i + 1 else size - i
i += 1
}
result
}
magicSquareDoublyEven(n).foreach(row => println(row.map(x => f"$x%2s ").mkString))
println(f"---%nMagic constant: ${(n * n + 1) * n / 2}%d")
}
You may also check:How to resolve the algorithm Anonymous recursion step by step in the Fortran programming language
You may also check:How to resolve the algorithm Catalan numbers step by step in the Stata programming language
You may also check:How to resolve the algorithm Web scraping step by step in the Erlang programming language
You may also check:How to resolve the algorithm Classes step by step in the Objeck programming language
You may also check:How to resolve the algorithm Sorting algorithms/Insertion sort step by step in the Phix programming language